Object deep clone in Javascript

Learn how to clone object without reference to deep elements.

/

Nov 19, 2020

(2 min read)

post cover

UPDATE: This is for handle objects with deep levels! The best way to clone objects with one level is with Object.create(object), but ensure that you don't receive deep objects.

Well, start with the following method that not works, but you can understand why to use other methods! Copy&paste in DevTools:

// This are method that not works!
const deepObject = { a: { b: 0 } };
let clonedDeepObject;

function modifyAndLog(object, value) {
   object.a.b = value;
   console.log('deepObject.a.b', deepObject.a.b, 'clonedDeepObject.a.b', object.a.b);
}

// Spread operator method
clonedDeepObject = { ...deepObject };
modifyAndLog(clonedDeepObject, 'string now');

// Object assign method
clonedDeepObject = Object.assign({}, deepObject);
modifyAndLog(clonedDeepObject, 'not works :(');

// Well this only works for first level, not to deep level


Use hacks!

The "hack" is use JSON to transform to string and parse again into an object. 

// Set to inital value
deepObject.a.b = 0;

// Use JSON.stringify into JSON.parse
clonedDeepObject = JSON.parse(JSON.stringify(deepObject));
modifyAndLog(clonedDeepObject, 'Now yes!!');


Now yes! We can clone objects with deep elements! But, what about performance?

Well, is too much better than use libraries like lodash, also you don't need to add external scritps.

Performance test: https://jsbench.me/8tkho3f0da

When use it and when not?

That depends on what do you need. When we talk about performance is about loops or concurrence process that need be fast processing. Don't worry about what use, it is in a client-side like a dashboard o similar.

(Well I still think that maybe you don't need lodash 🤫)

But if you need to do this in Node, think twice. Is too simple to create a file (also on client-side):

// cloneObject.js
module.exports = (object) => {
   return JSON.parse(JSON.stringify(object));
}

// Other file
const cloneObject = require('./cloneObject');
const myNewObject = cloneObject(myObject);


That's all! Happy code!

Matias L.

@matiaslopezd

Async thinking and await creating

Matias L.

Something about coding, business and life in english and spanish powered by Imprint 😎!

3 subscribers