0

I want to use javascript spread operator and I want the result of two different objects to merged using spread operator but it is not working as expected.

For instance, every time, for new request new data is coming and I want to append it a single object. For better consider, consider simple scenario:

const obj1 = {
    WellSchema: {
      well: [
        {wellName: 'check1', uwi: '9000000123'},
        {wellName: 'check2', uwi: '8000012432'}
      ]
    }
  }

const obj2 = {
    WellSchema: {
      well: [
        {wellName: 'check3', uwi: '2113120002'},
        {wellName: 'check4', uwi: '5679001211'},
        {wellName: 'check5', uwi: '0987652221'},
        {wellName: 'check6', uwi: '5345676542'}
      ]
    }
  }

const mutateIt = { ...obj1, ...obj2 }
console.log(mutateIt) 

The result I am getting is below:

{
    WellSchema: {
      well: [
        {wellName: 'check3', uwi: '2113120002'},
        {wellName: 'check4', uwi: '5679001211'},
        {wellName: 'check5', uwi: '0987652221'},
        {wellName: 'check6', uwi: '5345676542'}
      ]
    }
  }

Anyhow, intended result should be as:

{
        WellSchema: {
          well: [
            {wellName: 'check1', uwi: '9000000123'},
            {wellName: 'check2', uwi: '8000012432'}
            {wellName: 'check3', uwi: '2113120002'},
            {wellName: 'check4', uwi: '5679001211'},
            {wellName: 'check5', uwi: '0987652221'},
            {wellName: 'check6', uwi: '5345676542'}
          ]
        }
      }

Can you suggest, what is wrong in this case? Thanks

Owais
  • 854
  • 2
  • 13
  • 32
  • 3
    There's nothing wrong, that's what's supposed to happen. The spread operator doesn't magically give you a deep merge, so `WellSchema` from `obj2` just overwrites `WellSchema` from `obj1`. – jonrsharpe May 31 '18 at 08:41
  • What you want can be easily achieved by `array#concat`. – Hassan Imam May 31 '18 at 08:43
  • I can't in this case. I am liable to use spread operator as everything is coming dynamically. – Owais May 31 '18 at 08:44
  • 1
    Just use `const mutateIt = [ ...obj1.WellSchema.well, ...obj2.WellSchema.well ];` and you will get what you want – skovmand May 31 '18 at 08:46

0 Answers0