0

I would like to merge to two object into one in this example: https://codesandbox.io/s/vibrant-flower-y6c76

  const orig = {
    123: '123',
    abc: {
      p3: 'p3',
      p4: 'p4',
    },
  }

  const extended = {
    abc: {
      p1: 'p1',
      p2: 'p2',
      // ...orig.abc
    },
    def: 'def',
    ...orig,
  }

So that the extended object becomes:

{
    abc: {
      p1: 'p1',
      p2: 'p2',
      p3: 'p3',
      p4: 'p4'
    },
    def: 'def',
    123: '123',
  }

But right now the extended looks like below and it seems abc in orig overrides the one in extended. What is the right way to make it happen?

bunny
  • 1,797
  • 8
  • 29
  • 58
  • There's nothing built-in that does this in one step. But there are functions in jQuery, lodash, and underscore.js that will do recursive merges. – Barmar Jan 17 '20 at 22:48
  • 1
    Just move `...orig` to the top of your `extended` declaration, uncomment the `...orig.abc` line, and you should be good, **with the example you provided** (won't work if other properties are shared between the two – blex Jan 17 '20 at 22:51
  • If I move ...orig to the top, does that mean the abc in extended will override the one in orig? – bunny Jan 21 '20 at 08:16

0 Answers0