Search code examples
javascriptangularecmascript-6closuresnested-loops

Nested For of Loop Inside If Statement Only retains last value


I am having the weirdest issue with my nested for loop inside an Angular service. I have a service in which I am running the below forEach function with the data coming back from the service.

someArr.forEach(elem => {
 //do something with elem
    if(elem['users'].length >= 1) {
      for (let user of elem['users']) {
        console.log('>>> ', user['firstName'])
        elem['userFirstName'] = user['firstName'];
        elem['userLastName'] = user['lastName'];
        this.tempArr.push(elem);
      }
    } else {
       this.tempArr.push(elem);
    }
  })

The console.log is logging out the correct first and last name from the inner for loop, but only the last value is pushed to the tempArr. I thought using the let word resolves this closure issue. What am I missing here?


Solution

  • You aren't pushing a new object just another reference to the same one that you then mutate, when you push use Object.assign({}, elem) to create a new object.