How can I make a copy of an object in JavaScript?
This question already has an answer here:
You will have to map each property to the new array:
Simple one level clone can be made like this:
function clone(a, b) {
var prop;
for( prop in b ) {
b[prop] = a;
}
}
This will clone all properties from b
to a
. But keep all other properties in a
:
var a = {a: 9, c: 1},
b = {a: 1, b: 1};
copy(a, b); // {a: 1, b: 1, c: 1}
Deep Clone Object:
The above example will work when dealing with single level objects, but will make a confusion when multiply levels is present, take a look at this example:
var a = {},
b = { a: { a: 1 } }
clone(a, b);
a.a.a = 2;
console.log(a); // { a: { a: 2 } }
console.log(b); // { a: { a: 2 } }
The above example proves that the object inside aa
is the same as the one inside ba
.