deep copy javascript code example
Example 1: deep clone object javascript
JSON.parse(JSON.stringify(object))
Example 2: clone javascript object
let clone = Object.assign({}, objToClone);
Example 3: javascript deep clone
var cloned = JSON.parse(JSON.stringify(objectToClone));
Example 4: how to make a deep copy in javascript
JSON.parse(JSON.stringify(o))
Example 5: deep copy javascript
function copy(arr1, arr2) {
for (var i =0; i< arr1.length; i++) {
arr2[i] = arr1[i];
}
}
copy(arr1, arr2)
Example 6: deep clone javascript object
const deepCopyFunction = (inObject) => {
let outObject, value, key
if (typeof inObject !== "object" || inObject === null) {
return inObject // Return the value if inObject is not an object
}
// Create an array or object to hold the values
outObject = Array.isArray(inObject) ? [] : {}
for (key in inObject) {
value = inObject[key]
// Recursively (deep) copy for nested objects, including arrays
outObject[key] = deepCopyFunction(value)
}
return outObject
}