Array.prototype.toObjectByProperty( element=> )

T.J. Crowder tj.crowder at
Thu Aug 10 08:21:09 UTC 2017

On Wed, Aug 9, 2017 at 10:56 PM, Jordan Harband <ljharb at> wrote:
> TJ:
> I'm confused, can you provide a code sample?

So based on the signatures I mentioned [here][1]:

Object.from(iterable, indexer, target = Object.create(null))
// and
Map.from(iterable, indexer, target = new Map)

(although `byKey` or similar may be a better name), then for instance, if I
have this array in `stuff.users`:

    {id: "naveen.chowla", foreNames: "Naveen", surname: "Chowla"},
    {id: "tj.crowder", foreNames: "T.J.", surname: "Crowder"},
    {id: "jordan.harband", foreNames: "Jordan", surname: "Harband"}


stuff.usersById = Object.from(stuff.users, "id");

gives me a `stuff.usersById` that looks like this:

    "naveen.chowla":  {id: "naveen.chowla", foreNames: "Naveen", surname:
    "tj.crowder":     {id: "tj.crowder", foreNames: "T.J.", surname:
    "jordan.harband": {id: "jordan.harband", foreNames: "Jordan", surname:

*(Those are the same objects.)*

That's the common case: A known-in-advance string key. I do that all the
time. But the `indexer` parameter can also be a Symbol or a function; the
function receives the entry and returns the key, so it can be a computed
key. The test for what the `indexer` is is trivially simple and fast and
need be done only once.

I can supply the target as a third argument if I want to create it myself
for any reason (specific prototype, or I already have one with partial data
and I'm adding more, etc):

stuff.usersById = Object.from(newUsers, "id", stuff.usersById);

The `Map` version does the same thing where the result (and optional third
parameter) is a `Map` instead.

-- T.J. Crowder

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the es-discuss mailing list