简体   繁体   中英

Javascript array item overwritten

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);
    }
}

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);
  }
}

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM