I have a better idea: how about `Object.from(iter)`, where `iter` is
an iterable of `[key, value]` pairs?

```
const a = [
  {id: "tjc", name: "T.J. Crowder"},
  {id: "nc", name: "Naveen Chawla"},
  {id: "lh", name: "Lachlan Hunt"}
];

const object = Object.from(a.map(o => [o.id, o.name]))
```

We already have `Object.entries(object)`, returning an array of `[key,
value]` pairs, so this would effectively be the inverse of that -
`Object.from(Object.entries(object))` would be equivalent to
`Object.assign({}, object)` assuming native prototypes are unmodified.

(Yes, it's like `_.zipObject(pairs)` from Lodash)
-----

Isiah Meadows
m...@isiahmeadows.com

Looking for web consulting? Or a new website?
Send me an email and we can get started.
www.isiahmeadows.com


On Sat, Aug 5, 2017 at 4:42 PM, Darien Valentine <valentin...@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 ]));
> ```
>
> Although I’m also puzzled by the suggestion that reducing to an object is an
> abuse,
> I do find I wish there were a complement to `Object.entries`:
>
> ```
> // Object to pairs, and therefore map, is simple:
>
> const map = new Map(Object.entries(obj));
>
> // Converting back is also simple ... but not exactly expressive:
>
> [ ...map ].reduce((acc, [ key, val ]) => Object.assign(acc, { [key]: val
> }));
> ```
>
> Something like `Object.fromEntries` would not provide as much sugar for the
> OP case as `toObjectByProperty`, but it gets pretty close and has the
> advantage
> of being more generic; `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. Both map<->object and array<->object cases would become more
> expressive — plus it follows pretty naturally from the existence of
> `Object.entries` that there might be a reverse op.
>
> ```
> Object.fromEntries(a.map(a.map(member => [ member.name, member ])));
> ```
>
> In other words, `Object.fromEntries(Object.entries(obj))` would be
> equivalent in
> effect to `Object.assign({}, obj)`.
>
> Would that adequately address this case you think? My sense is that it’s
> better to supply generic helpers before more specific helpers when it comes
> to built-ins.
>
> _______________________________________________
> es-discuss mailing list
> es-discuss@mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>
_______________________________________________
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss

Reply via email to