Home > Software engineering >  How can i sum objects in array by the properties?
How can i sum objects in array by the properties?

Time:10-12

i would like to have 2 number of level in my array but i dont know how to do that.

there is my init array :

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]);
          }
         }
        }

that give me this :

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

I tried to do this but its not the result i expected :

 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);
          }
       } 
      }

result:

Array []

html: 4

java: 1

length: 0

The sum didnt work.

Someone know how can i do that ?

CodePudding user response:

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)

CodePudding user response:

Is this what you are looking for?

https://stackblitz.com/edit/angular-ivy-yu5g1k?file=src/app/app.component.ts

  • Related