We're a place where coders share, stay up-to-date and grow their careers.
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 }), {} );
the [item[key]] tripped me up initially haha.
[item[key]]
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.
Thanks manπͺ
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 π :
the
[item[key]]
tripped me up initially haha.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.
Thanks manπͺ