I have a big JS object with many nested objects. For example:
var A = { 'b': { c: [1], d: { e: { f: 'g' } } } };
I need to create an object "B" looks like the object "A", but array "b.c" should contain another one item:
var B = { 'b': { c: [1, 2], d: { e: { f: 'g' } } } };
The object "A" should not be changed.
I know two ways to do it:
1 Deep clone JS object:
var B = JSON.parse(JSON.stringify(A)); // or with lodash: _.cloneDeep(A) B.b.c.push(2);
2 Clone only those objects and arrays that I need to clone:
var B = Object.assign({}, A); B.b = Object.assign({}, B.b); B.b.c = B.b.c.slice(0); B.b.c.push(2);
I'm afraid that the first way is resource intensive. I don't need to clone all object. And the second way has too many code. There is a little object in my example but it can be really big objects in my application.
How to create the object "B" of the most optimal way?