对对象数组中的相似键求和 [英] Sum similar keys in an array of objects

查看:24
本文介绍了对对象数组中的相似键求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象数组,如下所示:

<预><代码>[{'name': 'P1',价值":150},{'name': 'P1',价值":150},{'name': 'P2',价值":200},{'name': 'P3',价值":450}]

我需要将同名对象的所有值相加.(可能还有其他数学运算,例如计算平均值.)对于上面的示例,结果将是:

<预><代码>[{'name': 'P1',价值":300},{'name': 'P2',价值":200},{'name': 'P3',价值":450}]

解决方案

首先遍历数组并将名称"推入另一个对象的属性.如果属性存在,则将值"添加到属性的值,否则将属性初始化为值".构建此对象后,遍历属性并将它们推送到另一个数组.

这是一些代码:

var obj = [{'名称':'P1','值':150},{'名称':'P1','值':150},{'名称':'P2','值':200},{'名称':'P3','值':450}];var 持有人 = {};obj.forEach(函数(d){如果(holder.hasOwnProperty(d.name)){持有人[d.name] = 持有人[d.name] + d.value;} 别的 {持有人[d.name] = d.value;}});var obj2 = [];for (var prop in holder) {obj2.push({ name: prop, value:holder[prop] });}console.log(obj2);

希望这会有所帮助.

I have an array of objects like the following:

[
    {
        'name': 'P1',
        'value': 150
    },
    {
        'name': 'P1',
        'value': 150
    },
    {
        'name': 'P2',
        'value': 200
    },
    {
        'name': 'P3',
        'value': 450
    }
]

I need to add up all the values for objects with the same name. (Probably also other mathematical operations like calculate average.) For the example above the result would be:

[
    {
        'name': 'P1',
        'value': 300
    },
    {
        'name': 'P2',
        'value': 200
    },
    {
        'name': 'P3',
        'value': 450
    }
]

解决方案

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.

Here is some code:

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);

Hope this helps.

这篇关于对对象数组中的相似键求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆