0

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

1 Answer 1

2

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} };
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.