Learn how you can implement fast deep cloning of objects in JavaScript.
When you’re writing a clone function in JS, you should consider a case when one of the source fields is an object itself.
If that’s the case, you need to recursively clone that object as well.
function clone(obj) {
var clone = {};
for(var i in obj) {
if(obj[i] != null && typeof(obj[i]) == "object")
clone[i] = clone(obj[i]);
else
clone[i] = obj[i];
}
return clone;
}
For convenience, you can add the clone function to the Object.prototype
.
Object.defineProperty(Object.prototype, "clone", { value: clone, enumerable: false });
This will allow you to use the clone
function on all JS objects.
If you’re looking for a prebuilt solution, you can use the lodash function.