Ramda-如何合并2个或更多对象数组

问题描述 投票:0回答:1

我正在尝试使用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"
    }
  ]
]

任何帮助将不胜感激。

ramda.js
1个回答
0
投票

使用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>
© www.soinside.com 2019 - 2024. All rights reserved.