To convert an array into an object we will create a function and give it 2 properties, an array and a key.
const convertArrayToObject = (array, key) => {};
We will then reduce the array, and create a unique property for each item based on the key we have passed in.
We also need to remember to set an initial Value, and also pass in the current value (...obj in the below).
const convertArrayToObject = (array, key) => {
const initialValue = {};
return array.reduce((obj, item) => {
return {
...obj,
[item[key]]: item,
};
}, initialValue);
};
So now if we log out our function (passing in the array and our key which is a unique identifier in this case the id property) we will see our array is now an object.
console.log(
convertArrayToObject(
[
{ id: 111, name: 'John', age: 29 },
{ id: 112, name: 'Sarah', age: 25 },
{ id: 122, name: 'Kate', age: 22 },
{ id: 123, name: 'Tom', age: 21 },
{ id: 125, name: 'Emma', age: 24 },
],
'id',
),
);
returns
{
111:{ id: 111, name: 'John', age: 29 },
112:{ id: 112, name: 'Sarah', age: 25 },
122:{ id: 122, name: 'Kate', age: 22 },
123:{ id: 123, name: 'Tom', age: 21 },
125:{ id: 125, name: 'Emma', age: 24 }
}
We can now easily look up data in our array by an id and use it as required.
Top comments (1)
Much simpler to use
Object.fromEntries
- also runs about twice as fast: