Nodejs: how to clone an object

If I clone an array, I use cloneArr = arr.slice()

I want to know how to clone an object in nodejs.


Solution 1:

For utilities and classes where there is no need to squeeze every drop of performance, I often cheat and just use JSON to perform a deep copy:

function clone(a) {
   return JSON.parse(JSON.stringify(a));
}

This isn't the only answer or the most elegant answer; all of the other answers should be considered for production bottlenecks. However, this is a quick and dirty solution, quite effective, and useful in most situations where I would clone a simple hash of properties.

Solution 2:

Object.assign hasn't been mentioned in any of above answers.

let cloned = Object.assign({}, source);

If you're on ES6 you can use the spread operator:

let cloned = { ... source };

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

Solution 3:

There are some Node modules out there if don't want to "roll your own". This one looks good: https://www.npmjs.com/package/clone

Looks like it handles all kinds of stuff, including circular references. From the github page:

clone masters cloning objects, arrays, Date objects, and RegEx objects. Everything is cloned recursively, so that you can clone dates in arrays in objects, for example. [...] Circular references? Yep!

Solution 4:

You can use lodash as well. It has a clone and cloneDeep methods.

var _= require('lodash');

var objects = [{ 'a': 1 }, { 'b': 2 }];

var shallow = _.clone(objects);
console.log(shallow[0] === objects[0]);
// => true

var deep = _.cloneDeep(objects);
console.log(deep[0] === objects[0]);