Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 570
fscore Avatar asked Oct 16 '17 01:10

fscore


People also ask

Does object assign overwrite?

The Javascript Object. assign is a method that copies all the properties from one or more source objects and stores them into a target object. And while working with multiple sources, the latter source properties overwrite the earlier ones.

Does object assign return new object?

The Object. assign() copies all enumerable and own properties from the source objects to the target object. It returns the target object.


3 Answers

You should manually merge deep object properties, try following:

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

or with spread operator

{
  ...state,
  boarding: {
    ...state.boarding,
    work: action.work
  }
}
like image 97
dhilt Avatar answered Nov 02 '22 05:11

dhilt


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.

like image 28
Cahil Foley Avatar answered Nov 02 '22 03:11

Cahil Foley


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.

like image 45
felixfbecker Avatar answered Nov 02 '22 03:11

felixfbecker