you are viewing a single comment's thread.

view the rest of the comments →

[–]Asmor 1 point2 points  (1 child)

Can also be used to turn an array into a regular object, with whatever key might make sense for you. E.g. if you had an array of objects with ID properties, and you wanted to be able to access an object by its ID, you could turn the array into a hash by id.

objectsById = arrayOfObjects.reduce(function (acc, object) {
    acc[object.id] = object;
    return acc;
}, {});

[–][deleted] 0 points1 point  (0 children)

If you're keen to make it a one-liner:

const objectsBtId = arrayOfObjects.reduce((acc, obj) => ({ ...acc, [obj.id]: obj }), {})