【问题标题】:Ramda - how to merge 2 or more arrays of objectsRamda - 如何合并 2 个或更多对象数组
【发布时间】:2020-08-19 13:51:54
【问题描述】:

我正在尝试使用 Ramda 将对象数组合并到一个干净的数组中,但我需要一些帮助。我有下面的示例 JSON。在此示例中,我有 2 个组,但组的数量可以是 3、4、10。我对每个组中的 tableItems 数组感兴趣。

const groups = [
  {
    id: '',
    name: '',
    tableItems: [
      {
        id: 1,
        name: 'John'
      },
      {
        id: 2,
        name: 'Paul'
      },
      {
        id: 3,
        name: 'Mary'
      }
    ]
  },
  {
    id: '',
    name: '',
    tableItems: [
      {
        id: 10,
        name: 'Brian'
      },
      {
        id: 20,
        name: 'Joseph'
      },
      {
        id: 30,
        name: 'Luke'
      }
    ]
  }
];

我尝试过这样的事情:

let mapValues = x => x.tableItems;
const testItems = R.pipe(
  R.map(mapValues)
)

然后我得到了 tableItems 的数组,现在我想将它们合并到一个数组中。

[
  [
    {
      "id": 1,
      "name": "John"
    },
    {
      "id": 2,
      "name": "Paul"
    },
    {
      "id": 3,
      "name": "Mary"
    }
  ],
  [
    {
      "id": 10,
      "name": "Brian"
    },
    {
      "id": 20,
      "name": "Joseph"
    },
    {
      "id": 30,
      "name": "Luke"
    }
  ]
]

任何帮助将不胜感激。

【问题讨论】:

  • 虽然,正如 OriDrori 指出的那样,这可以通过 chain(prop('tableItems'))(或 pipe(pluck('tableItems'), unnest))来完成,但它也是 ES6 中的简单单行代码:groups.flatMap(({tableItems}) => tableItems)
  • @ScottSauyet 原来如此简单...谢谢您的帮助

标签: ramda.js


【解决方案1】:

使用R.chain进行映射和展平,使用R.prop获取tableItems

const fn = R.chain(R.prop('tableItems'));

const groups = [{"id":"","name":"","tableItems":[{"id":1,"name":"John"},{"id":2,"name":"Paul"},{"id":3,"name":"Mary"}]},{"id":"","name":"","tableItems":[{"id":10,"name":"Brian"},{"id":20,"name":"Joseph"},{"id":30,"name":"Luke"}]}];

const result = fn(groups);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js"></script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-01
    • 2018-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-20
    • 2019-06-23
    相关资源
    最近更新 更多