简体   繁体   English

将一个数组的对象按键合并为一个object

[英]Merge objects of an array into one object by key

I am trying to merge objects of an array into one if they have the same key.如果它们具有相同的键,我正在尝试将数组的对象合并为一个。

Having this array:有这个数组:

let data = [
  { id: "1", cars: 5 }, 
  { id: "1", pasta: 2 },
  { id: "2", cars: 0 }, 
  { id: "2", pasta: 0 },
];

I would like to achieve this:我想实现这一点:

let data = [
  { id: "1", cars: 5, pasta: 2 },
  { id: "2", cars: 0, pasta: 0 },
];

I am looking for any solutions, but preferable ES6.我正在寻找任何解决方案,但最好是 ES6。

Here's a solution that combines the Array reduce method and the Object values method.这是一个结合了 Array reduce方法和 Object values方法的解决方案。 One benefit of this approach is that it is O(n) time complexity, which would only really matter if you had a ton of data, but still potentially more efficient than the solutions that include loops inside loops.这种方法的一个好处是它是 O(n) 时间复杂度,这仅在您拥有大量数据时才真正重要,但仍然可能比在循环中包含循环的解决方案更有效。

 let data = [ { id: "1", cars: 5 }, { id: "1", pasta: 2 }, { id: "2", cars: 0 }, { id: "2", pasta: 0 }, ]; const combined = Object.values(data.reduce((acc, el) => { acc[el.id] = {...acc[el.id], ...el }; return acc; }, {})); console.log(combined);

Using Array.prototype.reduce() :使用Array.prototype.reduce()

 let data = [ { id: "1", cars: 5 }, { id: "1", pasta: 2 }, { id: "2", cars: 0 }, { id: "2", pasta: 0 }, ] const result = data.reduce((items, item) => { const existingItem = items.find(({ id }) => id === item.id) if (existingItem) Object.assign(existingItem, item) else items.push({...item }) return items }, []) console.log(result) // Original array is left intact: console.log(data)

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

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