Reduce a JavaScript array into an indexed object
Use lodash
6%
Use Array.prototype.reduce
94%
31 votes · Closed
I faced some code that uses lodash/fromPairs
to build an indexed object:
import fromPairs from "lodash/fromPairs";
function lodashReduce(arr) {
return fromPairs(arr.map(item => [item, `my item is: ${item}`]));
}
But I know that ES6 has syntax that allows to do the same:
function es6Reduce(arr) {
return arr.reduce(
(obj, item) => ({ ...obj, [item]: `my item is: ${item}` }),
{}
);
}
In this codesandbox I wrote an example of thoses two implementations that uses this array as a parameter:
const arr = ["item1", "item2", "item3"];
And both functions return this object:
{"item1":"myitemis: item1","item2":"myitemis: item2","item3":"myitemis: item3"}
Can you tell me the version you prefer to read and use? Can you justify it in a few words?
EDIT 05-09-2018
I did a huge mistake on the native implementation because I love the spread/destructuring syntax (and love is blind).
Of course, it is always better not to create an object in a loop:
function BETTER_es6Reduce(arr) {
return arr.reduce(
(obj, item) => {
obj[item] = `my item is: ${item}`;
return obj
), {} );
}