DEV Community

Brian
Brian

Posted on

5 1

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.

Sentry image

See why 4M developers consider Sentry, β€œnot bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

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.

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free β†’

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay