1

Let's say I have:

var obj1 = {
    '0': 'a',
    '1': 'b'
    }

var obj2 = obj; // I want to create a new object with obj contents

obj1[2] = 'c' // Now I modify obj without modifying obj2

obj1 = obj2; // so I can restore obj later

However modifying obj also modificates obj2. How can I create a copy of obj1 that is independent of it?

1
  • 2
    You need to create a deep copy of the object Commented Dec 14, 2012 at 22:57

2 Answers 2

4

You need to do a deepCopy of the object.

var obj1 = {
    '0': 'a',
    '1': 'b'
};

var obj2 = deepCopy(obj1);

obj1[2] = 'c'

console.log(obj1);
console.log(obj2);

function deepCopy(obj) {
    var newObj = {};
    for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
            newObj[key] = obj[key];
        }
    }
    return newObj;
}​

Check Fiddle

Sign up to request clarification or add additional context in comments.

Comments

2

If your object is JSON-compatible (i.e., does not contain any functions as values, nor references to DOM nodes, etc):

var obj2 = JSON.parse(JSON.stringify(obj1));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.