DEV Community

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[curr[key]] = curr, acc), {});
// Basically everything inside parentheses will be evaluated, only the last value used will be only returned.

Enter fullscreen mode Exit fullscreen mode

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

Collapse
 
afewminutesofcode profile image
Aaron

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?

Collapse
 
ansaganio profile image
Ansagan Islamgali

There is no comma operator here

Thread Thread
 
vhoyer profile image
Vinícius Hoyer

yes, there is, it's right above the line of the "Basically everything..."

Collapse
 
frankdspeed profile image
Frank Lemanschik

there is no item var around it should be curr did you even write that code alone?

Collapse
 
vhoyer profile image
Vinícius Hoyer

Hey, man, I like code golfing too, but just because something can be written more concisely, it doesn't mean we should. Your second solution is kinda difficult to read because it's so cluttered and it also obligates people to know what the comma operator is and how it works. I just don't see how this is better than your first solution once the bundler will already minify the code for us, we don't need to write and read minified code, just be aware everyone, if you're gonna copy this, copy the first one, the people reading your code in the future will be happier :D