DEV Community

Brian
Brian

Posted on

Alternative to the spread operator

Alternative to the spread operator.

TLDR: Object.assign(object, object)

I was doing some work on a serverless function and I didn't have ES6 support so I had to figure out how to supplement the spread operator. Below is an example of the spread operator with some objects that hold some food.

const moreFood = {
'pizza': '🍕',
 'steak': '🥩',

}

const food = { 'chocolate': '🍫', 'icecream': '🍦', 'pizza': 'pizza', ...moreFood }

//results

{
'chocolate': '🍫', 
'icecream': '🍦',
'pizza': '🍕',
'steak': '🥩',
}

One of the alternatives to the spread operator is the Object.assign function. Here is the same function using the object.assign function.

const moreFood = {
'pizza': '🍕',
 'steak': '🥩',

}

const food = { 'chocolate': '🍫', 'icecream': '🍦', 'pizza': 'pizza' }

Object.assign(food, moreFood)

//results

{
'chocolate': '🍫', 
'icecream': '🍦',
'pizza': '🍕',
'steak': '🥩',
}

Side note:

If there is a duplicate key like in the example with pizza both the spread operator and the Object.assign function both will take what the right objects says pizza is.

Top comments (6)

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.