对对象数组中的类似键求和 [英] Sum similar keys in an array of objects
问题描述
我有一系列对象如下: -
I have an array of objects something like the following: -
[
{
'name': 'P1',
'value': 150
},
{
'name': 'P1',
'value': 150
},
{
'name': 'P2',
'value': 200
},
{
'name': 'P3',
'value': 450
}
]
我需要添加(求和)和可能的任何其他数学运算,例如计算平均值出现在其中的同名对象。类似于: -
I need to add (summation) and probably any other mathematical operation like calculate average the object with the same name appearing in it. Something like: -
[
{
'name': 'P1',
'value': 300
},
{
'name': 'P2',
'value': 200
},
{
'name': 'P3',
'value': 450
}
]
非常感谢我能得到的任何帮助。
Would appreciate any help that I can get.
提前致谢!
推荐答案
首先遍历数组并将'name'推送到另一个对象的属性中。如果属性存在,则将value添加到属性的值,否则将属性初始化为value。构建此对象后,遍历属性并将它们推送到另一个数组。
First iterate through the array and push the 'name' into another object's property. If the property exists add the 'value' to the value of the property otherwise initialize the property to the 'value'. Once you build this object, iterate through the properties and push them to another array.
以下是一些代码:
var obj = [
{ 'name': 'P1', 'value': 150 },
{ 'name': 'P1', 'value': 150 },
{ 'name': 'P2', 'value': 200 },
{ 'name': 'P3', 'value': 450 }
];
var holder = {};
obj.forEach(function (d) {
if(holder.hasOwnProperty(d.name)) {
holder[d.name] = holder[d.name] + d.value;
} else {
holder[d.name] = d.value;
}
});
var obj2 = [];
for(var prop in holder) {
obj2.push({name: prop, value: holder[prop]});
}
console.log(obj2);
希望这有帮助。
这篇关于对对象数组中的类似键求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!