Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 723
guilin 桂林 Avatar asked May 22 '11 15:05

guilin 桂林


People also ask

How do you clone an object in node?

Object. defineProperty(Object. prototype, 'clone', { enumerable: false, value: function() { var newObj = (this instanceof Array) ? [] : {}; for (i in this) { if (i == 'clone') continue; if (this[i] && typeof this[i] == "object") { newObj[i] = this[i].

What is the most efficient way to deep clone an object in JavaScript?

According to the benchmark test, the fastest way to deep clone an object in javascript is to use lodash deep clone function since Object. assign supports only shallow copy.


2 Answers

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.

like image 197
Kato Avatar answered Sep 28 '22 18:09

Kato


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

like image 24
Sam G Avatar answered Sep 28 '22 17:09

Sam G