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

时间:2016-07-10 17:46:23

标签: javascript arrays object

我有这个对象数组:

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

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

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

我怎样才能通过JavaScript实现这一目标?

2 个答案:

答案 0 :(得分:7)

您可以使用哈希表并使用总和生成一个新数组。



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




答案 1 :(得分:0)

您也可以使用linq.js提供的linq框架

这是我的代码使用linq.js,这几乎看起来像sql语句。

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


var aggregatedObject = Enumerable.From(arr)
        .GroupBy("$.name", null,
                 function (key, g) {
                     return {
                       name: key,
                       contributions: g.Sum("$.contributions")
                     }
        })
        .ToArray();

console.log(aggregatedObject);
<script src="http://cdnjs.cloudflare.com/ajax/libs/linq.js/2.2.0.2/linq.min.js"></script>