Reduce Array To Object Using Arrow Function
I'm playing around with the limits of array and arrow functions and I'm trying to convert this reduce function into an arrow function: var monthsById = months.reduce(function(resul
Solution 1:
You can return byId
in each iteration and wrap function body in parentheses ()
var months = [ { Id: 1 }, { Id: 2 }, { Id: 3 } ];
var monthsById = months.reduce((byId, month) => (byId[month.Id] = month, byId), {});
console.log(monthsById);
Solution 2:
You could use Object.assign
where you set a new property with computed property names and return the whole object.
var months = [{ Id: 1 }, { Id: 2 }, { Id: 3 }],
monthsById = months.reduce((byId, month) =>Object.assign(byId, { [month.Id]: month }), {});
console.log(monthsById);
An example with spreading.
var months = [{ Id: 1 }, { Id: 2 }, { Id: 3 }],
monthsById = months.reduce((byId, month) => ({ ...byId, [month.Id]: month }), {});
console.log(monthsById);
Post a Comment for "Reduce Array To Object Using Arrow Function"