DEV Community

Alternative to the spread operator

Brian on December 02, 2019

Alternative to the spread operator. TLDR: Object.assign(object, object) I was doing some work on a serverless function and I ...
Collapse
 
nmhillusion profile image
nmhillusion

good idea :)
if we want to keep the old value of pizza, how we do?

Collapse
 
brianmcoates profile image
Brian

If you just want the original value of pizza you just put the object to the right so in

Object.assign(moreFood, food)

and with the spread operator you can

{...moreFood, food}

Collapse
 
rhymes profile image
rhymes
const newFood = Object.assign({}, food, moreFood)

this will keep both intact and create a new object with the merged keys and values

Collapse
 
brianmcoates profile image
Brian

Love it thank you! Is there is there a way to do that with the spread operator as well?

Thread Thread
 
rhymes profile image
rhymes

Yes:

const newFood = { ...food, ...moreFood };
Collapse
 
lukepochron profile image
Luke

Nice post but most of us are here probably because IE doesn't support spread operators. Sadly it doesn't support Assign() either.