Yoni Mayer
Yoni Mayer

Reputation: 1238

JS | deep clone object partially

Is there a way to do a shallow copy all fields of obj1, but to do to deep clone of inner object deep_clone ?

let obj1 = {first: 'a', shallow_data: {a: 'a', b: 'b'}, deep_clone: {deep1: 1, deep2: 2} };

let obj2 = JSON.parse(JSON.stringify(obj1)); // full deep clone

so here I would like obj2 to be exactly the same as obj, except for deep_clone.

The motivation for this is that I have a big object and I need to improve performance and not to deep clone the entire object

Upvotes: 0

Views: 317

Answers (1)

Barmar
Barmar

Reputation: 782499

You can use spread syntax to combine shallow and deep copying.

let ob2 = {...obj1, deep_clone: JSON.parse(JSON.stringify(obj1.deep_clone)) };

...obj1 will shallow-copy the object, then the explicit assignment to the deep_clone: property will replace that property with deep copy.

If the deep_clone property is just one level deep, you can just use spread syntax there as well:

let ob2 = {...obj1, deep_clone: {...obj1.deep_clone} };

Upvotes: 2

Related Questions