DEV Community

loading...

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

Collapse
bradtaniguchi profile image
Brad • Edited

Nice!

I had to write one of these the other day.

Here's a slightly more concise version, where you throw out extra brackets and use an implicit return πŸ˜„ :

const convertArrayToObject = (array, key) =>
  array.reduce(
    (obj, item) => ({
      ...obj,
      [item[key]]: item
    }),
    {}
  );
Enter fullscreen mode Exit fullscreen mode

the [item[key]] tripped me up initially haha.

Collapse
afewminutesofcode profile image
Aaron Author

Thanks so much for pointing this out Brad! I have used this syntax for one liner map functions but had overlooked using it with reduce before. I am going to make sure I use it in the future, to keep my code more concise.

Collapse
nutritsio profile image
Serega

Thanks manπŸ’ͺ