循环遍历数组以查找具有匹配id的所有对象,并将这些对象合并到数组中的一个元素中

Loop through array to find all objects with matching ids, and merge those objects into one element in the array.

本文关键字:对象 数组 合并 一个 元素 查找 遍历 循环 id      更新时间:2023-09-26

我有一个对象数组。有些对象具有相同的id,但在某些键中具有不同的值。我想做的是循环遍历数组,找到所有id相同的对象,并将它们合并到数组中的一个对象中。

我的数组如下:

[{id: 1, letters: [a, b , c] }, {id: 2, letters: [d, e , f] }, {id: 1, letters: [ x, y, z] }]

我想要的结果是一个看起来像这样的数组:

[{id: 1, letters: [a, b , c, x, y, z] }, {id: 2, letters: [d, e , f] }] 

我正在使用lodash,但似乎无法获得

你可以尝试这样的东西(这是undercore.js,但我相信lodash非常相似)

data = [{id: 1, letters: ['a', 'b', 'c'] }, {id: 2, letters: ['d', 'e', 'f'] }, {id: 1, letters: ['x', 'y', 'z'] }]
groups = _.groupBy(data, function(obj) { return obj.id })
results = _.map(groups, function(groups) {
  id = groups[0].id;
  letters = _.chain(groups).map(function(obj) { return obj.letters }).flatten().uniq().value()
  return {id: id, letters: letters }
})
console.log(JSON.stringify(results))
// [{"id":1,"letters":["a","b","c","x","y","z"]},{"id":2,"letters":["d","e","f"]}]