Array.prototype.toObjectByProperty( element=>element.property )
T.J. Crowder
tj.crowder at farsightsoftware.com
Mon Aug 7 09:58:40 UTC 2017
On Sat, Aug 5, 2017 at 9:42 PM, Darien Valentine
<valentinium at gmail.com> wrote:
> 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 ]));
> ```
And:
On Sun, Aug 6, 2017 at 7:31 PM, Isiah Meadows
<isiahmeadows at gmail.com> wrote:
> I have a better idea: how about `Object.from(iter)`, where `iter` is
> an iterable of `[key, value]` pairs?
For the common case I have, that would require an additional transform
producing a lot of unnecessary temporary objects. I basically never
have `[ [key, value], [key, value] ...]` as my starting point where I
want this.
On Sat, Aug 5, 2017 at 9:42 PM, Darien Valentine
<valentinium at gmail.com> wrote:
> Although I’m also puzzled by the suggestion that reducing to an object is an
> abuse...
Let's ignore that, sorry; it's purely a distraction in this conversation.
> `toObjectByProperty` strikes me as rather specific for a built-in,
> especially since one might want to map by a derived value rather
> than a property.
Naveen's original post shows a callback that returns the key to use. I
also flag up using a callback to determine the value in my earlier
post on this. (In my post, I cater to the common case of a specific
property known in advance, but also allow for a callback; like
`String#replace`'s second parameter.)
> Would that adequately address this case you think?
For me, no; an unnecessary additional transform and too much memory churn.
> My sense is that it’s better to supply generic helpers before
> more specific helpers when it comes to built-ins.
In general, absolutely. But where the abstraction takes us into
unnecessary complexity and performance degradation, *slightly* more
specificity is fine in my view. I don't think my suggested
`Object.from` and `Map.from` are too specific.
-- T.J. Crowder
More information about the es-discuss
mailing list