3

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

2 Answers 2

9

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

Sign up to request clarification or add additional context in comments.

3 Comments

Wow! Exactly what I was looking for, I knew there are no limits :D may you add a reference what => (a, b) does? I don't fully understand it yet.
It will return last expression inside () in this case its accumulator parameter in reduce or byId
6

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

2 Comments

great! I thought of something like this, but didn't know how to assign the dynamic key :)
Thanks! You already received my +1 before ;) (And even posted about it).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.