DEV Community

Discussion on: Copying objects in JavaScript

Collapse
 
miketalbot profile image
Mike Talbot ⭐

The great thing about rfdc is that it super quickly clones real objects with cycles/functions/constructors etc. It is super quick at that.

If you need to quick clone something including enumerable properties but NOT any of that cool stuff rfdc does - then I use this that is a little quicker if you know that there won't be issues:

export function clone(o) {
    var newO, i

    if (typeof o !== 'object') {
        return o
    }
    if (!o) {
        return o
    }

    if (Array.isArray(o)) {
        newO = []
        for (i = 0; i < o.length; i += 1) {
            newO[i] = clone(o[i])
        }
        return newO
    }

    newO = {}
    for (i in o) {
        newO[i] = clone(o[i])
    }
    return newO
}

Collapse
 
sagar profile image
Sagar

Thanks, Mike for sharing this.

Collapse
 
ip127001 profile image
Rohit Kumawat

Thanks for sharing!

Collapse
 
sagar profile image
Sagar

looks good 👍🏻