When working in JavaScript sometimes we get a requirement where we need to merge two objects that may be deeply nested.
In this article, we will see how to handle that correctly.
Want to learn Redux in detail and build a complete food ordering app? check out my Mastering Redux course. Following is the preview of the app, we'll be building in the course. It's a great project you can add to your portfolio/resume.
Enroll for the course at just $12 instead of $19 until 26th May as a part of pre-launch offer.
Note that, in this app, I have used INR as the currency for displaying the prices but you can easily change it to USD or AUD or any other currency with a single configuration change in the app.
Let's get started
Let's say, we have a user object like this:
And we want to update this object with the new values. For example, when updating their user profile, the user enters new values, so we need to merge the previous object with the new updated object.
If the user updates only some values, we will have an object like this:
As you can see, the user object has a location
property with the city
and country
properties inside it. But in the updates object, we don’t have the country property, so how can we merge these objects?
Let’s try using some known ways.
Using Object.assign
As you can see, the location
property from the update object has completely replaced the previous location
object, so the country
property is lost.
This is because Object.assign does a shallow merge and not a deep merge. A shallow merge means it will merge properties only at the first level and not the nested level.
Here's a CodePen Demo.
Using Spread Operator
As you can see, this also produces the same result because Object.assign and the spread operator just shallow-merge the objects.
So to fix this and correctly merge two deeply nested objects, we can use the merge
method provided by a very popular lodash library.
Here's a CodePen Demo.
Using Lodash merge
Now, it works as expected and the country property is not lost in the merge.
Here's a CodePen Demo.
Lodash is the best utility library that has lots of functions for real-life applications. To explore other useful lodash methods, check out my this article.
Thanks for reading!
Check out my recently published Mastering Redux course.
In this course, you will learn:
- Basic and advanced Redux
- How to manage the complex state of array and objects
- How to use multiple reducers to manage complex redux state
- How to debug Redux application
- How to use Redux in React using react-redux library to make your app reactive.
- How to use redux-thunk library to handle async API calls and much more
and then finally we'll build a complete food ordering app from scratch with stripe integration for accepting payments and deploy it to the production.
Want to stay up to date with regular content regarding JavaScript, React, Node.js? Follow me on LinkedIn.