Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update Multiple Properties of an object with spread operator

I have a state in a reducer that looks like this:

// The current source/selection
const selection = {
  timespan: "-3660",
  customTimespan: false,
  pathIds: [''],
  source: undefined,
  direction: 0,
  appClassIds: []
};

What I want now is to update multiple properties (timespan and customTimeSpan), something like this (but this doesn't work):

{ ...state, 
  {
      timespan: action.timespan.value,
      customTimespan: action.timespan.value
  } 
};

How can I update multiple properties of a state?

like image 797
Diego Unanue Avatar asked Jan 26 '17 16:01

Diego Unanue


People also ask

Does spread operator overwrite property?

Using the spread operator to overwrite an object property It's a super clean syntax and easy to see which value we are overwriting. The only thing you must remember while using this method is that the order matters. If we, for instance, put the property we want to overwrite.

Does spread syntax overwrite?

Spread syntax allows us to utilize three periods to expand iterables such as arrays or objects and inherit the original iterable's values. In our case, we can use the spread operator to add on or overwrite additional style parameters.

Can you use spread operator on objects?

Spread syntax can be used when all elements from an object or array need to be included in a new array or object, or should be applied one-by-one in a function call's arguments list.


2 Answers

You need to remove the extra object closure from there

{ ...state, 
 timespan: action.timespan.value, 
 customTimespan: action.timespan.value
}

should work fine

If you wanted to do it in vanilla JS you could do this:

Object.assign({}, state, { timespan: action.timespan.value, customTimespan: action.timespan.value})

I think the spread operator is much cleaner and should go that route if you have access to it.

like image 164
finalfreq Avatar answered Nov 08 '22 18:11

finalfreq


You can also achieve the same using the spread operator which allows you to have the new values in an object, instead of having to hardcode them:

const selection = {
  timespan: "-3660",
  customTimespan: false,
  pathIds: [""],
  source: undefined,
  direction: 0,
  appClassIds: []
};

const newSelectionValues = {
  timespan: "-3600",
  customTimespan: true
};

const newSelection = { ...selection, ...newSelectionValues };
like image 31
Todor Kolev Avatar answered Nov 08 '22 20:11

Todor Kolev