0

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.

3
  • post the sample array/object here Commented Aug 2, 2019 at 9:35
  • 2
    Why are you using two indexes? this.org[x]['name'] = this.names[x] should be enough, the nested for is unnecessary, though you should loop the longest array first. May you share some examples, though? Commented Aug 2, 2019 at 9:36
  • seems you already are looping through this.org cuz GetDataById(this.org[i].userId), I assume that you will get only one user per id, then why another two loops? you simply can this.org[i].name=data.fullname after this.names.push(data.fullname). Commented Aug 2, 2019 at 9:47

1 Answer 1

1

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]
   }                  
})
Sign up to request clarification or add additional context in comments.

1 Comment

thanks so much. i was thinking that different arrays need different iterations

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.