Last Updated: September 30, 2021
·
5.453K
· fr0gs

Deep Copy object in Javascript

Full credit to [http://geniuscarrier.com/copy-object-in-javascript/][this webpage] who gathered several examples. This is just a nice reminder for me to have everything in the same place.

function deepCopy(oldObj) {
    var newObj = oldObj;
    if (oldObj && typeof oldObj === 'object') {
        newObj = Object.prototype.toString.call(oldObj) === "[object Array]" ? [] : {};
        for (var i in oldObj) {
            newObj[i] = deepCopy(oldObj[i]);
        }
    }
    return newObj;
}

2 Responses
Add your response

as far as i know JSON.parse(JSON.stringify(obj))1 is faster sadly the page with the benchmarks is currently under development

over 1 year ago ·

Nice trick! as soon as it is up I'll test it :D thank you

over 1 year ago ·