JavaScript Spread Operator

JavaScript QuickTip

When dealing with many different objects in JavaScript, sometimes you need to compile them all down together. The spread operator is a handy function for this and more.

Merging Objects

Sometimes, you need to easy recombine the elements of multiple objects, spread operator makes this simple.

Quick Example:
 
const veggies = { onions: 2, potatoes: 3 };
const fruits = { apples: 2, bananas: 4 };

const inventory = {...veggies, ...fruits};

/*
 { onions: 2, potatoes: 3, apples: 2, bananas: 4 }
*/

Combining Arrays 

In a similar way, the spread operator can help when trying to combine arrays. 

const user_list_1 = [232,567,344,74];const user_list_2 = [109,34,224,920];
const all_users = {...user_list_1, ...user_list_2};

/*
[
  232, 567, 344,  74,
  109,  34, 224, 920
]
*/


Similar Posts

Debugging AWS S3 for Rails Active Storage

It could be your CORS configuration for AWS S3 for Rails ActiveStorage

Rails Tech WebDev

Incentives

Companies seem to be completely blind to the insanity of the incentives they choose to track.

business

Simple Full Text Search in Rails

No gems, no dependencies, no complexity. Here’s a basic full text search to use on simpler, smaller rails apps.

Rails WebDev