Reduce array to object using arrow function

断了今生、忘了曾经 提交于 2019-12-21 06:56:08

问题


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(result, month) {
                            result[month.Id] = month;
                            return result;
                        }, {});

But I'm having trouble to return the map, since result[month.Id] = month; will return the month and not the map like in this approach:

var monthsById = months.reduce((byId, month) => byId[month.Id] = month, {});

So I'm looking for a single statement, that sets the value AND returns the object. (new Map() is not an option, since I need it in the regular {} format).

var months = [ { Id: 1 }, { Id: 2 }, { Id: 3 } ];

var monthsById = months.reduce((byId, month) => byId[month.Id] = month, {});

console.log(monthsById);

回答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);



回答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 } ];

var monthsById = months.reduce((byId, month) => Object.assign(byId, { [month.Id]: month }), {});

console.log(monthsById);


来源:https://stackoverflow.com/questions/49209046/reduce-array-to-object-using-arrow-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!