简体   繁体   English

遍历数组以查找具有匹配ID的所有对象,然后将这些对象合并为数组中的一个元素。

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

I have an array of objects. 我有一个对象数组。 Some of the objects have identical ids, but different values in certain keys. 一些对象具有相同的ID,但某些键中的值不同。 What I want to do is loop through the array and find all objects with identical ids, and merge them into one object in the array. 我想做的是遍历数组,找到所有具有相同ID的对象,然后将它们合并到数组中的一个对象中。

My array looks like this: 我的数组如下所示:

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

The outcome I want is an array that looks like this: 我想要的结果是一个看起来像这样的数组:

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

I'm using lodash, but just can't quite seem to get it 我正在使用lodash,但似乎不太明白

You can try something like this (that's underscore.js, but I believe lodash is very similar) 您可以尝试这样的事情(这是underscore.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"]}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM