DEV Community

Sarath
Sarath

Posted on

How to convert an array into an object in javascript

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.

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post

Top comments (1)

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

Much simpler to use Object.fromEntries - also runs about twice as fast:

const convertArrayToObject = (arr, key) => Object.fromEntries(arr.map(i=>[i[key], i])
Enter fullscreen mode Exit fullscreen mode

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay