loading...

How to merge two Objects or Arrays in JavaScript

dochan profile image Farhan Yahya ・1 min read

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!

Discussion

pic
Editor guide
Collapse
vladimirgal1012 profile image
Vladimir Gal

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 Author

Wow, thanks a lot