我有一个带有 Id 和年龄的 json 数组,如下所示
var arrayVal = [{id:"1", age: 20},{id:"2", age: 30},{id:"2", age: "20"},{id:"3", age: 20},{id:"5", age: 10}];
我想得到属于同一个id的年龄总和,如下所示
1 = 20
2 = 50
3 = 20
5 = 10
请找到下面的代码
$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);
}
我没有收到预期的输出。控制台显示输出为 202020。上面的代码出了什么问题?
最佳答案
用一个简单的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);
除了 reduce
解决方案更加紧凑和声明性之外,所提供代码的主要问题是由于强制。其中一个 age
值具有字符串 "20"
,强制将后续的 +
操作解释为字符串连接。
这个答案使用 +age
避免了这种意想不到的副作用,迫使 age
成为一个 Number
(这可以通过做 Number(age)
代替)。
关于javascript - 使用JS对Json数组中相同Id的值求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56536047/