使用JS在Json数组中的相同ID的总和 [英] Sum values of same Id in a Json Array using JS
问题描述
我有一个ID和年龄如下的json数组
I have a json array with Id and age as follows
var arrayVal = [{id:"1", age: 20},{id:"2", age: 30},{id:"2", age: "20"},{id:"3", age: 20},{id:"5", age: 10}];
我想获取属于相同ID的年龄总和,如下所示:
I want to get sum of age which belong to same id which will be as follows
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。上面的代码出了什么问题?
I don't receive the expected output. the console shows the output as 202020. What has gone wrong in the above code?
推荐答案
使用简单的 reduce()
操作:
With a simple reduce()
operation:
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
解决方案更加紧凑和声明性外,所提供代码的主要问题还在于 coercion 。 age
值之一具有字符串 20
,强制随后的 +
操作应解释为字符串连接。
Besides the reduce
solution being more compact and declarative, the main problem with the code provided is due to coercion. One of the age
values has the string "20"
, forcing the subsequent +
operations to be interpreted as string concatenation.
此答案可避免使用 + age $ c产生这种意外的副作用$ c>,将
age
强制为 Number
(可以通过执行明确显示数字(年龄)
)。
This answer avoids this unexpected side-effect using the +age
, forcing age
to be a Number
(this could be made explicit by doing Number(age)
instead).
这篇关于使用JS在Json数组中的相同ID的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!