如何合并对象并求和一些重复对象的值? [英] How to merge objects and sum just some values of duplicate objects?
本文介绍了如何合并对象并求和一些重复对象的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个对象数组:
Let's say I have an array of objects:
[
1: {name: "john", id: 200, points: "333"},
2: {name: "alice", id: 302, points: "20"},
3: {name: "alice", id: 302, points: "13"},
4: {name: "kevin", id: 501, points: "3"},
5: {name: "adam", id: 999, points: "100"},
6: {name: "adam", id: 999, points: "30"},
7: {name: "adam", id: 999, points: "60"},
]
如您所见,它们已经被排序(使用lodash).我要实现的是我要合并具有相同ID的对象并添加点.所以看起来像这样:
As you can see, they're already sorted (using lodash). What I want to achieve is I want to merge objects with the same id and add the points. So it looks like this:
[
1: {name: "john", id: 200, points: "333"},
2: {name: "alice", id: 302, points: "30"},
3: {name: "kevin", id: 501, points: "3"},
4: {name: "adam", id: 999, points: "190"},
]
我正在使用React和Lodash.该阵列中大约有7000条记录.
I'm using React and Lodash. There are about 7000 records in that array.
推荐答案
没有Lodash的解决方案
var a = [
{name: "john", id: 200, points: "333"},
{name: "alice", id: 302, points: "20"},
{name: "alice", id: 302, points: "13"},
{name: "kevin", id: 501, points: "3"},
{name: "adam", id: 999, points: "100"},
{name: "adam", id: 999, points: "30"},
{name: "adam", id: 999, points: "60"},
];
var o = {};
a.forEach((i) => {
var id = i.id;
i.points = parseInt(i.points)
if (!o[id]) {
return o[id] = i
}
return o[id].points = o[id].points + i.points
})
console.log(o)
var a2 = []
Object.keys(o).forEach((key) => {
a2.push(o[key])
})
console.log(a2)
https://jsbin.com/dififukiqa/edit?js,console
这篇关于如何合并对象并求和一些重复对象的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文