Array.prototype.toObjectByProperty( element=>element.property )
kdex at kdex.de
Sat Aug 5 14:08:40 UTC 2017
On Saturday, August 5, 2017 1:35:35 PM CEST T.J. Crowder wrote:
> On Sat, Aug 5, 2017 at 11:18 AM, Naveen Chawla
> <naveen.chwl at gmail.com> wrote:
> > I've often needed to cache array elements by a unique key each
> > element has, for quick access.
> Yes, please. I've needed this in every codebase I've ever worked on. For
> me, having it in the standard lib would be a win. (Yes, you can easily do
> it by (ab)using `reduce`, but A) It's arguably an abusage [one I'm
> increasingly resigning myself to], and B) Why keep re-writing it?)
Why do you consider this an abuse of `reduce`? The problem at hand is to
reduce an iterable to a single value with certain properties. And I would like
to think that reducing is what `reduce` is supposed to do. ;)
Could you please elaborate on that?
> Some off-the-cuff suggestions:
> 1. Put it on `Object`: `Object.from`.
> 2. Have a Map version: `Map.from`.
> 3. Accept any iterable, not just an array.
> 4. Accept a string, Symbol, or callback: If a string or Symbol, use the
> matching property as the key for the result. If a callback, use the
> callback's return value (your example).
> 5. Optionally accept the object or map rather than creating a new one.
> So something like:
> `Object.from(iterable, indexer, target = Object.create(null))`
> `Map.from(iterable, indexer, target = new Map)`
> -- T.J. Crowder
-------------- next part --------------
A non-text attachment was scrubbed...
Size: 833 bytes
Desc: This is a digitally signed message part.
More information about the es-discuss