Question

I have two objects. At one point in my code I want a copy of the first object to be stored in a second object.

So long all works fine. No to the strange part. If i make any changes to the first object the same change is applied to the second object (which isn't the intention). I guess thats because some kind of referens between the two is keept.

Exampel illustrating the problem:

//First object
var person = {
    value: 1,
    item: 2
}

//Second object
var objSum = {
    contain: person,
    info: "other stuff"
}

//Apply change to first object
person.value = 55;
//Echoing second object
console.log(objSum);
    alert("done");

The log outputs: contain => item: 2, value: 55. info: "other stuff"

I want it to be: contain => item: 2, value: 1. info: "other stuff"

It's probably something simple, but i cant get my head around it. Why is this happening, and how can I prevent it

Was it helpful?

Solution

You need to clone the person-object when assigning it to objSum.contain, otherwise you are assigning a reference to the original object. Most easy way is with jquery:

var objSum = {
    contain: jQuery.extend({}, person);
};

or

var objSum = {
    contain: jQuery.extend(true, {}, person);
};

if person itself also contains objects

OTHER TIPS

You need to clone the object 'person', not referencing it.

There are several ways to clone the object and also there is famous question and answer already...

What is the most efficient way to deep clone an object in JavaScript?

For your case, using JSON method will be fine.

//First object
var person = {
    value: 1,
    item: 2
}

//Second object
var objSum = {
    contain: JSON.parse(JSON.stringify(person)), //clone object
    info: "other stuff"
}

//Apply change to first object
person.value = 55;
//Echoing second object
console.log(objSum);
alert("done");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top