我有这个对象数组:
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实现这一点呢?
您可以使用一个哈希表并生成一个包含所需总和的新数组。
null
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);
您还可以使用linq.js提供的linq框架来完成此操作
下面是我使用linq.js编写的代码,这几乎是sql语句。
null
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>