deep copy of objects javascript code example
Example 1: deep clone object javascript
JSON.parse(JSON.stringify(object))
Example 2: 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 3: how to deep copy an object in javascript
const obj1 = { a: 1, b: 2, c: 3 };
const s = JSON.stringify(obj1);
const obj2 = JSON.parse(s);