Reputation: 3252
I have a JavaScript array of objects, which is initialised with some values. I want to copy those values to a new array of objects, but without referencing to the original one, so I can then manipulate the new object.
I tried objectOptions.concat()
like in this sample code but it then deletes also the referenced original object:
var objectOptions = [{option1: 'value1', someOption: 'value2'}];
function objectClean(){
var newObjectOptions = objectOptions.concat();
for(var i in newObjectOptions ) {
delete newObjectOptions[i]['someOption'];
}
return newObjectOptions ;
};
Upvotes: 0
Views: 125
Reputation: 71939
If your object is simple enough and JSON-compatible (i.e., only contains objects, arrays and primitives, no DOM references, no Regex objects, no circular references etc.), the simplest way to clone is:
var clone = JSON.parse(JSON.stringify(original));
Otherwise, you'll need a deep copy function, like the one found on this answer*:
function clone(obj){
if(obj == null || typeof(obj) != 'object')
return obj;
var temp = obj.constructor(); // changed
for(var key in obj)
temp[key] = clone(obj[key]);
return temp;
}
* Be careful! The accepted answer to that question is a jQuery only solution, and terribly overrated!
Upvotes: 3
Reputation: 4204
var copyme = {/*object with properties which are to be copied in another object*/};
var copy = {};
for (var attr in copyme) {
if (copyme.hasOwnProperty(attr)) copy[attr] = clone(copyme[attr]);
}
Upvotes: 1