DEV Community

Discussion on: Copying objects in JavaScript

Collapse
 
sagar profile image
Sagar

There is a cool library available for cloning objects efficiently called rfdc (Really Fast Deep Clone).

const clone = require("rfdc")();

const user = {
  id: 1,
  name: "Leanne Graham",
  username: "Bret",
  email: "Sincere@april.biz",
  phone: "1-770-736-8031 x56442",
  website: "hildegard.org",
  company: {
    name: "Romaguera-Crona",
    catchPhrase: "Multi-layered client-server neural-net",
    bs: "harness real-time e-markets",
  },
};

const nextUser = clone(user);

console.log(user === nextUser); // This will return false because object have differnt reference.
Collapse
 
ip127001 profile image
Rohit Kumawat

Thanks for such a cool suggestion.
Infact after your comment, I have looked into it and its comparision with other libraries. I think it's very efficient.

Collapse
 
sagar profile image
Sagar

👍🏻

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 👍🏻