js deepcopy 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: how to make a deep copy in javascript

JSON.parse(JSON.stringify(o))

Example 4: deep copy js

//recursive deep copy of object
function dup(o) {
    // "string", number, boolean
    if(typeof(o) != "object") {
        return o;
    }
    
     // null
    if(!o) {
        return o; // null
    }
    
    var r = (o instanceof Array) ? [] : {};
    for(var i in o) {
        if(o.hasOwnProperty(i)) {
            r[i] = dup(o[i]);
        }
    }
    return r;
}