首页 > 解决方案 > 如何通过属性对数组中的对象求和?

问题描述

我想在我的数组中有 2 个级别,但我不知道该怎么做。

有我的初始化数组:

this.users = response["users"];
    this.users = JSON.parse(JSON.stringify(this.users));


    this.technos = response["technos"];
    this.technos = JSON.parse(JSON.stringify(this.technos));


    for(let z in this.technos){
      for (let i in this.users){
        for( let x in this.users[i].techno){
          if(this.users[i].techno[x].name == this.technos[z].name){
           this.dataUsers.push(this.users[i].techno[x]);
          }
         }
        }

给我这个:

[
  {
    "name": "java",
    "niveau": 3
  },
  {
    "name": "java",
    "niveau": 1
  },
  {
    "name": "html",
    "niveau": 5
  },
  {
    "name": "html",
    "niveau": 4
  }
]

我试图这样做,但它不是我预期的结果:

 for(let k in this.dataUsers){
          if(this.dataUsers[k].name == this.technos[z].name){
            this.dataNiveau[this.technos[z].name] = 0;
            this.dataNiveau[this.technos[z].name] += this.dataUsers[k].niveau;
            console.log(this.dataNiveau);
          }
       } 
      }

结果:

Array []

html: 4

java: 1

length: 0

总和没有用。

有人知道我该怎么做吗?

标签: angulartypescript

解决方案


Not sure if this is what you want. Check the solution.

const dataUsers = [{
  "name": "java",
  "niveau": 3
}, {
  "name": "java",
  "niveau": 1
}, {
  "name": "html",
  "niveau": 5
}, {
  "name": "html",
  "niveau": 4
}]


const sum = {};

for (let item of dataUsers) {
  if (sum[item.name]) {
    sum[item.name] += item.niveau
  } else {
    sum[item.name] = item.niveau
  }
}


console.log('sum----', sum)


推荐阅读