This page looks best with JavaScript enabled

Merge Arrays / Objects using Spread Operator

 ·   ·  ☕ 1 min read

You can use the ... operator to perform black magic in Javascript.

Consider the below example -

1
2
3
4
5
6
const arrNums = [1, 2, 3];
const arrMoreNums = [4, 5, 6];

const allNums = [...arrNums, ...arrMoreNums];
console.log("allNums: ", allNums);
// [ 1, 2, 3, 4, 5, 6 ]

This is much much more efficient than writing code to go through two loops and merging them.

The same is true for objects.

1
2
3
4
5
6
const objNums = { a: 1, b: 2, c: 3 };
const objMoreNums = { x: 98, y: 99, z: 100 };

const objAllNums = { ...objNums, ...objMoreNums };
console.log("objAllNums: ", objAllNums);
//{ a: 1, b: 2, c: 3, x: 98, y: 99, z: 100 }

And no - you cannot convert types through spread. That is dark black magic and is not possible at this time.

1
2
const crossConn = [...arrNums, ...objNums];
// TypeError: objNums is not iterable

You could however use similar iterables to merge array elements and an object - for what it’s worth.

1
2
3
const crossConn = [...arrNums, { ...objNums }];
console.log("crossConn: ", crossConn);
// [ 1, 2, 3, { a: 1, b: 2, c: 3 } ]
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things