Update nested object using Object.assign

I have the following object. This object gets assigned a new value when the user clicks on a button.

state = {
  title: '',
  id: '',
  imageId: '',
  boarding: {
    id: '',
    test: '',
    work: {
      title: '',
      id: ''

My updated object looks like:
state = {
  title: 'My img',
  id: '1234',
  imageId: '5678-232e',
  boarding: {
    id: '0980-erf2',
    title: 'hey there',
    work: {
      title: 'my work title',
      id: '456-rt3'

Now I want to update just work object inside state and keep everything the same. I was using Object.assign() when the object was not nested but confused for nesting.
Object.assign({}, state, { work: action.work });

My action.work has the entire work object but now I want to set that to boarding but this replaces everything that is in boarding which is not what I want.


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You should manually merge deep object properties, try following:

Object.assign({}, state, { 
  boarding: Object.assign({}, state.boarding, {
    work: action.work

or with spread operator
  boarding: {
    work: action.work

Method 2

If merging them manually as @dhilt suggested is not an option, take a look at lodash’s merge.

You can use mergeWith if you want to customise the merge behaviour, e.g. merge arrays instead of overriding.

Method 3

You can use Object.assign to update nested objects, for example:

Object.assign(state.boarding, { work: action.work })

This will update the state in place with the new work properties.

Method 4

If you just want to update work, you don’t need any sort of merge. Just do

state.boarding.work = action.work;

Are you concerned with immutability, you can make a copy of state and then update work.

Method 5

I can see you’re using Redux. There’s a great article in the docs about updating objects in an immutable way. I suggest you read it: http://redux.js.org/docs/recipes/reducers/ImmutableUpdatePatterns.html

Also, people usually use libraries for this, like Immutable.js or seamless-immutable, which don’t make your code that disgusting to look at 🙂

Method 6

> Use JavaScript spread operator:

{ ...user, staff_information: { nid: e.target.value }

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x