1

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?

Ildar
  • 3,808
  • 7
  • 45
  • 81

1 Answers1

1

JSON.stringify/.parse is certainly the easiest way to deep-clone a (simple) object but, as you said, it involves serializing and parsing objects and it's totally not the most efficient way.

Luckily, things have become nicer from ES6. And with ESNext, you can spread objects too:

var B = { ...A };

Of course, there's still your problem with b.c, but that has to be adjusted manually:

var B = { ...A, b: { ...A.b, c: [1, 2] }};

Here's Babel's plugin for object spread operator: https://babeljs.io/docs/plugins/transform-object-rest-spread/

MaxArt
  • 22,200
  • 10
  • 82
  • 81