1

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)

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

tevemadar
  • 12,389
  • 3
  • 21
  • 49
Ryan H
  • 2,620
  • 4
  • 37
  • 109
  • *what am I missing?* - that it's not a recursive operation. `...application` takes the fields of `application`, so `applicant` and `income`, then `...customer` overwrites `applicant` with its own field. – tevemadar Nov 19 '21 at 15:07
  • Does this answer your question? [How to deep merge instead of shallow merge?](https://stackoverflow.com/questions/27936772/how-to-deep-merge-instead-of-shallow-merge) – tevemadar Nov 19 '21 at 15:11

2 Answers2

1

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}
};
James
  • 20,957
  • 5
  • 26
  • 41
0

You can do this easily with lodash

const merged = _.merge(customer, application)

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

Rob
  • 12,659
  • 4
  • 39
  • 56
  • I get that lodash has a lot of useful utility methods, but the OP neither mentioned or asked for a lodash solution – Icepickle Nov 22 '21 at 12:37