Categories
JavaScript Answers

How to convert an array of objects to object with key value pairs with JavaScript?

Spread the love

To convert an array of objects to object with key value pairs with JavaScript, we can use the Object.fromEntries method.

For instance, we write:

const array = [{
  name1: "value1"
}, {
  name2: "value2"
}]

const map = array.map(a => {
    return Object.entries(a)
  })
  .flat()
const obj = Object.fromEntries(map)
console.log(obj)

We call array.map with a callback to return the key-value pair of each object in array as a nested array.

Then we call flat to flatten the array.

Next, we call Object.fromEntries with the map key-value pair nested array to combine the key-value pairs into an object.

Therefore, obj is {name1: 'value1', name2: 'value2'}.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *