Search code examples
javascriptarraysjavascript-objects

Dynamically add key/value array of names into array of objects


I have an array of names. I also have an array of objects. I would like to iterate through the array of objects and also iterate through the the array of names and add the name into the objects. For example, name[0] goes into object[0], and so on.

I have this code:

this.individualSrv.GetDataById(this.org[i].userId).subscribe(data => {
  this.names.push(data.fullname)
  for (var x = 0; x < this.org.length; x++) {
    for (var i in this.names) {
      this.org[x]['name'] = this.names[i]
    }                    
   }                  
})

Right now, the last name in the array is added to each object in the array.


Solution

  • You don't need to nest 2 loops to do that. Just make sure that both arrays have the same length.

    this.individualSrv.GetDataById(this.org[i].userId).subscribe(data => {
      this.names.push(data.fullname)
      for (var x = 0; x < this.org.length; x++) {
          this.org[x]['name'] = this.names[x]
       }                  
    })