I am experiencing some strange behavior when trying to do the following:
- Create a base JSON object
- Create a for loop and send the base object to a new function to be modified
- The new function should modify one element of the base JSON object and then send it back
Here is my sample code:
var object = [ {"test": "Test1", "id": 0}, {"test": "Test2", "id": 0}, {"test": "Test3", "id": 0}, {"test": "Test4", "id": 0}, ]; for(var i=0; i < 4; i++) { newObject(i).then(function(obj){ console.log(obj); }) } function newObject(i) { return new Promise(function(resolve, reject){ var newObject = object; newObject[i].id = i; resolve(newObject); }) } What I would expect to receive back from console.log(obj) is 4 times a different object like this
[ {"test": "Test1", "id": 0}, {"test": "Test2", "id": 0}, {"test": "Test3", "id": 0}, {"test": "Test4", "id": 0}, ]; [ {"test": "Test1", "id": 0}, {"test": "Test2", "id": 1}, {"test": "Test3", "id": 0}, {"test": "Test4", "id": 0}, ]; [ {"test": "Test1", "id": 0}, {"test": "Test2", "id": 0}, {"test": "Test3", "id": 2}, {"test": "Test4", "id": 0}, ]; [ {"test": "Test1", "id": 0}, {"test": "Test2", "id": 0}, {"test": "Test3", "id": 3}, {"test": "Test4", "id": 0}, ]; However what I end up receiving is 4 times the exact same object like this
[ {"test": "Test1", "id": 0}, {"test": "Test2", "id": 1}, {"test": "Test3", "id": 2}, {"test": "Test4", "id": 3}, ];
var newObjectisn't a copy of your initial object, it's a reference to it. You're changing the same single object with each and every loop.