Skip to content
Advertisement

Group array to an object in javascript

Hello apologies if this has been asked before but I can’t search for the right term to find something useful.

Suppose if I had an array of

JavaScript

how would I change this to an object like so?

JavaScript

Advertisement

Answer

Edit – just noticed the format of your data – map reduce may not work for you, but still a similar principle:

JavaScript

Old answer:

You can use a reduce pattern.

JavaScript

The reduce method gets the accumulated value, the current value and the array index. In this case we are using the spread operator to add the next value to the object.

Note that the ( before the object definition is needed, so that JS doesn’t confuse it with a code block.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement