I'm declaring the following array.
let arr = [
{ id:"aa", vals:[1,2,3] },
{ id:"cc", vals:[3,4,5] },
{ id:"bb", vals:[2,3,4] }];
Printing it in the console confirms the expectation as each element has two fiels: a string id
and a number array vals
. Then, I perform reduce(...)
on it like this.
let reduction = arr.reduce((a,b) => a[b.id] = b, {});
My expectation is a single object with the fields corresponding to the ID values of the iterated array, i.e. aa, bb and cc, where each of those three fields contains the corresponding element from the original array.
What I get is only the last one element following the expectation, while the first two get convoluted somehow, being equipped with additional fields. Please note that I'm talking about changes in the original array! According to the docs: The reduce() method does not change the original array.
What am I missing?
The end-game desire is to simply convert an array to a dictionary by reducing it to a single instance but with arbitrarily added fields. There's a bunch of resources to get inspiration from out there. So this question relates only to this unexpected behavior.
Arrays in JavaScript are objects and all objects in JavaScript are passed by reference. In other words, whenever you alter any property on your object, all its references are going to point to the same object, with changed property.
In your case, you can consider returning a new object each time, like this:
let reduction = arr.reduce((a,b) => ({...a, [b.id]: b}), {});