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.