DEV Community

Farhan Yahya
Farhan Yahya

Posted on

How to merge two Objects or Arrays in JavaScript

So for a while now I've know the spread operator in JavaScript. I have been using it for while now but I never knew it worked for objects too.

Merging two Arrays

let a = [1, 2, 3, 4, 5];
let b = [6, 7, 8, 9, 10];
let c = [...a, ...b];
console.log(c);
// output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Merging two Objects

let a = {
  name: 'Han'
};
let b = {
  age: 98
};
let c = {...a, ...b};
console.log(c);
// output: {name: 'Han', age: 98}

I hope you also know now. Thanks for reading!

Top comments (2)

Collapse
 
mrdreix profile image
Vladimír Gál • Edited

It is pretty useful in deconstructing too.

const a = {
   name: 'Maria',
   sureName: 'Smith',
   age: 22
}
const {name, ...rest} = a

console.log(name)
// output: 'Maria'

console.log(rest)
//output: {sureName: 'Smith', age: 22}
Collapse
 
dochan profile image
Farhan Yahya

Wow, thanks a lot