javascript - 使用JS对Json数组中相同Id的值求和

标签 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}];

我想得到属于同一个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/

相关文章:

ios - 按与当前位置的距离对数组进行排序

javascript - 创建系统为 3 名员工提供积分,每次我单击其中一个按钮时,我都会为所选用户提供 1 分 -

javascript - 自动递增动态文本框 div ID 和结果显示在来自另一个 jquery 的递增 div ID 中?

javascript - 为什么 this.$el 给出未定义的错误,但 $(this.el) 在 Backbone View 中的渲染函数内部工作?

Javascript onclick 事件在页面加载时触发

c - 数组中分配的值发生变化,我不明白为什么

javascript - 将数组中的对象分开,并在新数组中为每个 id 按 id 排序

javascript - Bootstrap 4 导航选项卡更改页面而不是更改选项卡内容

javascript - 如何正确检测IE11以上版本?

java - 从 HashMap <String , String> 获取 JsonArray String 值