如何在对象数组中合并重复项并对特定属性求和?

nun*_*uda 10 javascript arrays object

我有这个对象数组:

var arr = [
    {
        name: 'John',
        contributions: 2
    },
    {
        name: 'Mary',
        contributions: 4
    },
    {
        name: 'John',
        contributions: 1
    },
    {
        name: 'Mary',
        contributions: 1
    }
];
Run Code Online (Sandbox Code Playgroud)

...我希望合并重复,但总结他们的贡献.结果如下:

var arr = [
    {
        name: 'John',
        contributions: 3
    },
    {
        name: 'Mary',
        contributions: 5
    }
];
Run Code Online (Sandbox Code Playgroud)

我怎么能用JavaScript实现这一目标?

Nin*_*olz 11

您可以使用哈希表并生成带有总和的新数组.

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);
Run Code Online (Sandbox Code Playgroud)

  • 减少:https://jsfiddle.net/mplungjan/Lr84keqy/ (5认同)
  • 您可以使用全新的ES6 Map对象:`var result = new Map(); arr.forEach((element)=> {if(result.get(element.name))result.set(element.name,result.get(element.name)+ element.contributions);否则为result.set(element。名称,element.contributions);}); console.log(result);` (2认同)
  • @mplungjan 我喜欢你的方法 (2认同)