object.assign javascript copy array code example
Example 1: javascript clone object
var x = {myProp: "value"};
var xClone = Object.assign({}, x);
//Obs: nested objects are still copied as reference.
Example 2: 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
}