如何合并对象数组中的重复项并对特定属性求和? [英] How to merge duplicates in an array of objects and sum a specific property?

查看:33
本文介绍了如何合并对象数组中的重复项并对特定属性求和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个对象数组:

var arr = [
    {
        name: 'John',
        contributions: 2
    },
    {
        name: 'Mary',
        contributions: 4
    },
    {
        name: 'John',
        contributions: 1
    },
    {
        name: 'Mary',
        contributions: 1
    }
];

... 我想合并重复项但总结他们的贡献.结果如下:

... and I want to merge duplicates but sum their contributions. The result would be like the following:

var arr = [
    {
        name: 'John',
        contributions: 3
    },
    {
        name: 'Mary',
        contributions: 5
    }
];

我如何使用 JavaScript 实现这一点?

How could I achieve that with JavaScript?

推荐答案

您可以使用哈希表并生成一个包含您需要的总和的新数组.

You could use a hash table and generate a new array with the sums, you need.

var arr = [{ name: 'John', contributions: 2 }, { name: 'Mary', contributions: 4 }, { name: 'John', contributions: 1 }, { name: 'Mary', contributions: 1 }],
    result = [];

arr.forEach(function (a) {
    if (!this[a.name]) {
        this[a.name] = { name: a.name, contributions: 0 };
        result.push(this[a.name]);
    }
    this[a.name].contributions += a.contributions;
}, Object.create(null));

console.log(result);

这篇关于如何合并对象数组中的重复项并对特定属性求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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