使用JS的Json数组中相同ID的总和

tha*_*ndu 1 javascript arrays

我有一个ID和年龄如下的json数组

var arrayVal = [{id:"1", age: 20},{id:"2", age: 30},{id:"2", age: "20"},{id:"3", age: 20},{id:"5", age: 10}];
Run Code Online (Sandbox Code Playgroud)

我想获得属于相同ID的年龄总和,如下所示

1 = 20
2 = 50
3 = 20
5 = 10
Run Code Online (Sandbox Code Playgroud)

请找到下面的代码

$scope.TestFunc = function()
{
var tot = 0;
var arrayVal = [{id:"1", age: 20},{id:"2", age: 30},{id:"2", age: "20"},{id:"3", age: 20},{id:"5", age: 10}];
for(var i=0; i <arrayVal.length; i++ )
{
  for(var j=1; j<arrayVal.length - i; j++ )
  {
    if(arrayVal[i].id == arrayVal[j].id)
    {
      tot = arrayVal[i].age.valueOf() + arrayVal[j].age.valueOf();
    }
    else{
      tot = tot + arrayVal[i].age;
    }
  }
}
console.log("-----total----"+tot);
}
Run Code Online (Sandbox Code Playgroud)

我没有收到预期的输出。控制台将输出显示为202020。上面的代码出了什么问题?

Rob*_*sen 7

简单的reduce()操作:

const array = [{id:"1", age: 20},{id:"2", age: 30},{id:"2", age: "20"},{id:"3", age: 20},{id:"5", age: 10}];

const ages = array.reduce((a, {id, age}) => (a[id] = (a[id] || 0) + +age, a), {});

console.log(ages);
Run Code Online (Sandbox Code Playgroud)


除了reduce解决方案更加紧凑和声明式之外,所提供代码的主要问题还在于强制性。其中一个age值具有字符串"20",强制将后续+操作解释为字符串连接。

该答案使用,避免了这种意外的副作用+age,强制age将其设为a Number(可以通过这样做Number(age)来明确表示)。