Member-only story

Merge Two Objects And Array To Object In JavaScript

How two merge two objects or transform an array into an object in JavaScript

David Dal Busco
2 min readApr 2, 2020
Photo by Ludovic Migneault on Unsplash

I share one trick a day until the end of the COVID-19 quarantine in Switzerland, April 19th 2020. Seventeen days left until hopefully better days.

To be really honest with you, I did not had that much idea for today’s blog post. For my defense, this is the eighteenth blog post I write every day in a row, it might explains my lack of today’s inspiration 😅.

That being said, I will share with you the following two tricks which I find useful.

Merge Two Objects

Thanks to the introduction of Spread Operator in ES6, it is now more than ever before really easy to merge two objects. No more loops, comparison or rocket science, the merge operation can be written in a single line of code.

It is also worth to notice that in case both objects would contain the same key, the value of the last object, “the one on the right in the line of code”, is the winning value.

const bruno = {
sing: true,
song: 'Treasure'
};

const ratm = {
type: 'band',
song: 'Bombtrack'
};

const result = {...bruno, ...ratm};

console.log(result);

// -> {sing: true, song: "Bombtrack", type: "band"}

--

--

David Dal Busco
David Dal Busco

Written by David Dal Busco

Freelancer by day | Creator of Juno.build by night

No responses yet