Merge Objects or Arrays with the `Spread` operator

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.

That's me!

I’m Ajay Karwal. I write about my experiences as a front-end developer. If you enjoy my content, please consider supporting what I do.

Become a PatronBuy me a coffee