簡體   English   中英

遍歷數組以查找具有匹配ID的所有對象,然后將這些對象合並為數組中的一個元素。

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

我有一個對象數組。 一些對象具有相同的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,但似乎不太明白

您可以嘗試這樣的事情(這是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