如何通过添加数字从对象数组中获取唯一值

时间:2017-01-10 07:18:14

标签: javascript wso2 dashboard wso2carbon

我在wso2碳仪表板上工作。我的表包含2个字段(名称和编号)。我在对象中有重复的名称,但编号不同。我想要添加数字的唯一名称。

[
        {
        "Name":"Abc",
        "number":2
        },
        {
        "Name":"bcd",
        "number":3
        },
        {
        "Name":"Abc",
        "number":5
        }

预期产出

[
{
"name":"Abc",
"Number":7
},
{
"name":"bcd",
"Number":3
}
]

我使用java脚本来完成这样的任务。请帮帮我

1 个答案:

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