Array.prototype.toObjectByProperty( element=>element.property )
T.J. Crowder
tj.crowder at farsightsoftware.com
Sat Aug 5 11:35:35 UTC 2017
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?)
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))`
and
`Map.from(iterable, indexer, target = new Map)`
-- T.J. Crowder
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20170805/d69e0162/attachment.html>
More information about the es-discuss
mailing list