DEV Community

Discussion on: How to convert an array into an object in javascript

Collapse
 
vhoyer profile image
Vinícius Hoyer • Edited

I know that this post is from 2019, but I guess I will offer some more recent way of writing this:

const convert = (array, keyName) => Object.fromEntries(
  array.map(item => [item[keyName], item])
);
Enter fullscreen mode Exit fullscreen mode

Or if you want to remove the key from the object:

const convert = (array, keyName) => Object.fromEntries(
  array.map(({ [keyName]: key, ...item }) => [key, item])
);
Enter fullscreen mode Exit fullscreen mode