1

I have an array of 71 objects:

var data = []

I populate this with data coming from a database that contains both static and dynamic elements of the objects that populate data.

angular.forEach(returnData,function(value,index) {
  if(!Array.isArray(value)) {
    tempObject[key] = value;
  }
});
for(i = 0; i < 71; i++) {
  data.push(tempObject);
}

So, in angular, I grab every element that is static from the return data, create an object of it, and repeat that same object 71 times. So the data might start out something like this:

[
  {'a': 1,
   'b': 2,
   'd': 7
  },
  {'a': 1,
   'b': 2,
   'd': 7
  }
]

I then go and grab all of the elements that are passed back as arrays and try and add them to the data array.

However, as soon as I add the first element, it sets that same element for every object in the array.

Meaning that data[0]['c'] = 11; will result in:

[
  {'a': 1,
   'b': 2,
   'c': 11,
   'd': 7
  },
  {'a': 1,
   'b': 2,
   'c': 11,
   'd': 7
  }
]

even though I haven't touched the second index in the array. And when I update the second index it will update the first index as well. I'm sure there is something that I'm missing here.

Thanks!

2 Answers 2

2

You're just pushing a reference to tempObject into 71 different positions in your data array. Therefore data[0], data[1], and so on are all pointing to the same object which is why you see changes reflected across the array.

If you want to actually push 71 separate instances, you have to clone tempObject every time you push it on to the array.

Last I checked, the most efficient way to clone a plain old JavaScript object was to string-ify and then re-parse:

data.push(JSON.parse(JSON.stringify(tempObject)));
Sign up to request clarification or add additional context in comments.

1 Comment

data.push({...tempObject}) or data.push([...tempObject]) result the same.
1

You said it yourself: the array contains the same object 71 times. Not 71 copies of an object, but the same single object referenced 71 times. Thus, changing that object via any of those references will be reflected in all references.

Comments

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.