how to do deep copy in javascript code example
Example 1: how to make a deep copy in javascript
JSON.parse(JSON.stringify(o))
Example 2: deep copy javascript
function copy(arr1, arr2) {
for (var i =0; i< arr1.length; i++) {
arr2[i] = arr1[i];
}
}
copy(arr1, arr2)
Example 3: deep clone javascript object
const deepCopyFunction = (inObject) => {
let outObject, value, key
if (typeof inObject !== "object" || inObject === null) {
return inObject
}
outObject = Array.isArray(inObject) ? [] : {}
for (key in inObject) {
value = inObject[key]
outObject[key] = deepCopyFunction(value)
}
return outObject
}
Example 4: deep copy js
function dup(o) {
if(typeof(o) != "object") {
return o;
}
if(!o) {
return o;
}
var r = (o instanceof Array) ? [] : {};
for(var i in o) {
if(o.hasOwnProperty(i)) {
r[i] = dup(o[i]);
}
}
return r;
}