Let's say you have an array of user
objects, all with unique IDs, but you want to group them in a single object by their id
s.
// These are your only users
const users = [
{ id: 1, name: "Paul" },
{ id: 2, name: "Ringo" },
{ id: 3, name: "George" },
];
An easy way to do this using Array.prototype.reduce
without creating too many intermediary objects would be:
const usersGroupedById = users.reduce((res, u) => (res[u.id] = u, res), {})
I have a feeling every linter in the world would cry linty tears upon seeing this. But honestly, I kind of like it!
Does this code offend you? How would you do this?
My alternatives were:
/// Create objects willy-nilly because they are cheap
users.reduce((res, u) => ({ ...res, [u.id]: u }), {})
// Use Object.assign to avoid spread syntax, still create a new object for every iteration
users.reduce((res, u) => Object.assign(res, { [u.id]: u }), {})
// Arguably more readable version of the featured solution
users.reduce((res, u) => {
res[u.id] = u;
return res;
}, {})
Top comments (2)
Not that it matters, but for the sake of offering an alternative solution I'd probably lean more towards
Object.fromEntries
thanreduce
.totally matters and I wish I could heart this twice -- I've never seen
Object.fromEntries
!