FWIW, while I find needs like this common, too, where Map is sensible
instead of
Object, it does come out pretty clean:

const a = [
  {id: "tjc", name: "T.J. Crowder"},
  {id: "nc", name: "Naveen Chawla"},
  {id: "lh", name: "Lachlan Hunt"}

const index = new Map(a.map(member => [ member.name, member ]));

Although I’m also puzzled by the suggestion that reducing to an object is
an abuse,
I do find I wish there were a complement to `Object.entries`:

// Object to pairs, and therefore map, is simple:

const map = new Map(Object.entries(obj));

// Converting back is also simple ... but not exactly expressive:

[ ...map ].reduce((acc, [ key, val ]) => Object.assign(acc, { [key]: val

Something like `Object.fromEntries` would not provide as much sugar for the
OP case as `toObjectByProperty`, but it gets pretty close and has the
of being more generic; `toObjectByProperty` strikes me as rather specific
for a
built-in, especially since one might want to map by a derived value rather
a property. Both map<->object and array<->object cases would become more
expressive — plus it follows pretty naturally from the existence of
`Object.entries` that there might be a reverse op.

Object.fromEntries(a.map(a.map(member => [ member.name, member ])));

In other words, `Object.fromEntries(Object.entries(obj))` would be
equivalent in
effect to `Object.assign({}, obj)`.

Would that adequately address this case you think? My sense is that it’s
better to supply generic helpers before more specific helpers when it comes
to built-ins.
es-discuss mailing list

Reply via email to