我在wso2碳仪表板上工作。我的表包含2个字段(名称和编号)。我在对象中有重复的名称,但编号不同。我想要添加数字的唯一名称。
[
{
"Name":"Abc",
"number":2
},
{
"Name":"bcd",
"number":3
},
{
"Name":"Abc",
"number":5
}
预期产出
[
{
"name":"Abc",
"Number":7
},
{
"name":"bcd",
"Number":3
}
]
我使用java脚本来完成这样的任务。请帮帮我
答案 0 :(得分:2)
将Array#reduce
方法与参考对象一起使用。
var data = [{
"Name": "Abc",
"number": 2
}, {
"Name": "bcd",
"number": 3
}, {
"Name": "Abc",
"number": 5
}];
// object for index reference
var ref = {};
// iterate and generate the array
var res = data.reduce(function(arr, o) {
// check index already defined
if (!(o.Name in ref)) {
// if not defined then define index
ref[o.Name] = arr.length;
// and push the element
// you can also use
// arr.push({Name:o.Name, number:o.number});
arr.push(Object.assign({}, o));
} else {
// if index already defined update the number
arr[ref[o.Name]].number += o.number;
}
// return the array reference
return arr;
// set initial value as empty array
}, []);
console.log(res);