0

I have the following code.

The code iterates over a collection of jsonRow objects, they are pushed onto a jsonRows array, then the jsonRow object is reset property by property.

This reset causes the jsonRow object in the jsonRows array to become affected. Any clues to this behavior?

for(iterating over collection of jsonRow objects){
    if(0 < jsonRow.id.length && 0 < jsonRow.title.length){
        jsonRows.push(jsonRow);

        console.log('jsonRow in jsonRows is intact', jsonRows);

        for(var prop in jsonRow){ 
            jsonRow[prop] = '';                     
        }
        console.log('jsonRow properties in jsonRows are ""', jsonRows);
    }
}
pigfox
  • 1,301
  • 3
  • 28
  • 52

3 Answers3

1

The objects in the jsonRows and the one you "reset" are the same. Javascript passes parameters by references. If you don't want the change to be reflected in the objects you push in the array, you need to clone the objects.

For example:

for(iterating over collection of jsonRow objects){
  if(0 < jsonRow.id.length && 0 < jsonRow.title.length){
    jsonRows.push(Object.assign({}, jsonRow));

    console.log('jsonRow in jsonRows is intact', jsonRows);

    for(var prop in jsonRow){ 
        jsonRow[prop] = '';                     
    }
    console.log('jsonRow properties in jsonRows are ""', jsonRows);
  }
}
Community
  • 1
  • 1
Quentin Roy
  • 7,677
  • 2
  • 32
  • 50
1

It is because you push a reference of the JSON object in the array. If you now change the JSON object which points to the same reference, everything which points to the reference will have the new value. You have to copy the JSON object and then push it on the array, then the object has an new reference.

ebimanuel
  • 186
  • 1
  • 4
0

Want a new Object?

if(!Object.create){
  Object.create = function(obj){
    function F(){}; F.prototype = obj;
    return new F;
  }
}
var newObj = Object.create(oldObj);
// now use your loop
StackSlave
  • 10,613
  • 2
  • 18
  • 35