Javascript pushing objects into array changes entire array

There are two ways to use deep copy the object before pushing it into the array. 1. create new object by object method and then push it.

servermessagelist = []; 
servermessagelist.push(Object.assign({}, servermessage));
  1. Create an new reference of object by JSON stringigy method and push it with parse method.

    servermessagelist = []; servermessagelist.push(JSON.parse(JSON.stringify(servermessage));

This method is useful for nested objects.


servermessagelist: new Array() empties the array every time it's executed. Only execute that code once when you originally initialize the array.


When you add the object to the array, it's only a reference to the object that is added. The object is not copied by adding it to the array. So, when you later change the object and add it to the array again, you just have an array with several references to the same object.

Create a new object for each addition to the array:

servermessage = {"color1":"yellow", "color2":"white", "message1":"", "message2":""};
servermessagelist.push(servermessage);
servermessage = {"color1":"green", "color2":"red", "message1":"", "message2":"nice work"};
servermessagelist.push(servermessage);

When you push servermessage into servermessagelist you're really (more or less) pushing a reference to that object. So any changes made to servermessage are reflected everywhere you have a reference to it. It sounds like what you want to do is push a clone of the object into the list.

Declare a function as follows:

function cloneMessage(servermessage) {
    var clone ={};
    for( var key in servermessage ){
        if(servermessage.hasOwnProperty(key)) //ensure not adding inherited props
            clone[key]=servermessage[key];
    }
    return clone;
}

Then everytime you want to push a message into the list do:

servermessagelist.push( cloneMessage(servermessage) );