DEV Community

loading...

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

Collapse
mdor profile image
Marco Antonio Dominguez • Edited

This is good, anyhow is an antipattern, it should be something like:

const convertArrayToObject = (array, key) => 
  array.reduce((acc, curr) => {
    acc[curr[key]] = curr;
    return acc;
  }, {});

// Even concise
const convertArrayToObject = (array, key) => 
  array.reduce((acc, curr) =>(acc[item[key]] = item, acc), {});
// Basically everything inside parentheses will be evaluated, only the last value used will be only returned.

In this way, you avoid the spread op which is a way expensive than a single assignment

Collapse
afewminutesofcode profile image
Aaron Author

Thanks for taking the time to help me and others out here! I am going to read up on the Comma operator in JavaScript developer.mozilla.org/en-US/docs/W... do you have any other resources you recomend here?