Array.prototype.toObjectByProperty( element=>element.property )

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


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

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

```js
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`:

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

then

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

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

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

*(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):

```js
stuff.users.push(...newUsers);
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

[1]: https://esdiscuss.org/topic/array-prototype-toobjectbyproperty-element-
element-property#content-2
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20170810/092eac93/attachment-0001.html>


More information about the es-discuss mailing list