Home > Net >  Javascript overwrite part of a nested object with object merging
Javascript overwrite part of a nested object with object merging

Time:11-20

I'm working on a JS project where I need to override some values in my object which contains nested objects.

I'd normally use the following:

const merged = { ...application, ...customer }

So that any data inside of customer can override the application.

However, in my example, customer is overriding the entire applicant nested object and I just need to override the name within that object?

I've put together a JS fiddle which can be found here, what am I missing?

const customer = {
  applicant: {
    first_name: 'john'
  }
}

const application = {
  applicant: {
    first_name: 'edward',
    age: 50
  },
  income: {
    salary: 500
  }
}

const merged = { ...application, ...customer }

console.log(merged)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

In merged I expect the first_name to be "John" whilst everything else remains in tact.

CodePudding user response:

The properties you want to replace via spreading have to be at the top level of the object. In this case you take the top-level properties of application, which are applicant and income, and then replace the applicant property with that from customer. If you want the name to be replaced you would need something like

const merged = {
  ...application, 
  {applicant: ...application.applicant, ...customer.applicant}
};

CodePudding user response:

You can do this easily with lodash

const merged = _.merge(customer, application)

https://lodash.com/docs/4.17.15#merge

  • Related