RSS Amplifier

Ajay Karwal · Jul 10, 2020

Merge Objects or Arrays with the `Spread` operator

0
Sign in to vote or save

Ajay Karwal

09 July, 2020

Using the Spread operator (...) you can quickly merge multiple Objects or Arrays together.

const user = {
	name: 'Ajay Karwal',
	twitter: '@ajaykarwal'
};
const appearance = {
	eyes: 'Brown',
	hair: 'Black',
	glasses: true
};
const profile = { ...user, ...appearance };
console.log(profile);

The result is a single merged Object

{
  eyes: "Brown",
  glasses: true,
  hair: "Black",
  name: "Ajay Karwal",
  twitter: "@ajaykarwal"
}

The same can be applied to Arrays.

const fruit = ['apples', 'bananas', 'strawberries'];
const veg = ['potatoes', 'spinach', 'cauliflower'];
const lunch = [...fruit, ...veg];
console.log(lunch);
// ["apples", "bananas", "strawberries", "potatoes", "spinach", "cauliflower"]

You can even merge Objects and Arrays, though the results might not be what you’re expecting.

Read the original on ajaykarwal.com

Comments

Nothing yet. Say the first thing.

    Sign in to join the conversation.