Merge Two Objects And Array To Object In JavaScript

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

Photo by Ludovic Migneault on Unsplash

Merge Two Objects

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"}

Array To Object

// {name: string, genre: string}[]
const bands = [
{
name: 'Ratm',
genre: 'rock'
},
{
name: 'Bruno',
genre: 'Pop'
}
];
// {ratm: string, bruno: string}
const artists = bands.reduce(
(obj, item) => {
obj[item.name] = item.genre;
return obj;
},
{});


console.log(artists);

// {Ratm: "rock", Bruno: "Pop"}

Summary

Freelancer by day | Creator of DeckDeckGo by night | Organizer of the Ionic and IndieHackers Zürich Meetup

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store