Possible Duplicate:
What is the most efficient way to clone a JavaScript object?
How to clone js object with out reference like these:
{ ID: _docEl,
Index: next,
DocName: _el
}
Any ideas?
Copy an Object With Object.assign() was the most popular way to deep copy an object. Object. assign() will copy everything into the new object, including any functions. Mutating the copied object also doesn't affect the original object.
JavaScript provides 3 good ways to clone objects: using spread operator, rest operator and Object.
You'll have to iterate over the object and make copies of all its properties.
And then if any of its properties are also objects, assuming you want to clone those too, you'll have to recurse into them.
There's various methods for doing this here: What is the most efficient way to clone a JavaScript object?
Here's how I'd do it, based on thomasrutter's suggestion (untested code):
function cloneObj(obj) {
var clone = {};
for (var i in obj) {
if (obj[i] && typeof obj[i] == 'object') {
clone[i] = cloneObj(obj[i]);
} else {
clone[i] = obj[i];
}
}
return clone;
}
You can use jQuery.extend:
// Shallow copy
var newObject = jQuery.extend({}, oldObject);
// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);
The following post is so helpful:
What is the most efficient way to deep clone an object in JavaScript?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With