loading...

re: Copying objects in JavaScript VIEW POST

TOP OF THREAD FULL DISCUSSION
re: There is a cool library available for cloning objects efficiently called rfdc (Really Fast Deep Clone). const clone = require("rfdc")(); const u...
 

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
}

 

Thanks, Mike for sharing this.

 
 
code of conduct - report abuse