Sometimes, we want to create object from array with JavaScript.
In this article, we’ll look at how to create object from array with JavaScript.
How to create object from array with JavaScript?
To create object from array with JavaScript, we call 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 dynamicArray.map
with a callback that maps each entry to an array that has the key and value respectively.
Then we call Object.fromEntries
with the array to return an object with the year
values as the keys and the objects as the values.
Conclusion
To create object from array with JavaScript, we call the Object.fromEntries
method.