Categories
JavaScript Answers

How to create object from array with JavaScript?

Spread the love

To create object from array with JavaScript, we can use the Object.fromEntries method.

For instance, we write

const dynamicArray = ["2007", "2008", "2009", "2010"];
const obj = Object.fromEntries(
  dynamicArray.map((year) => [
    year,
    {
      something: "based",
      on: year,
    },
  ])
);

console.log(obj);

to call Object.fromEntries with an array that we get from the map method called with a callback that returns arrays with the key and value of each property.

We use Object.fromEntries to convert the nested key-value pair array to an object.

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 *