Nodejs: how to clone an object


Question

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

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

1
86
11/28/2018 8:32:32 PM

Accepted Answer

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.

166
6/27/2013 8:27:32 PM

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


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon