Array.prototype.toObjectByProperty( element=> )

Jussi Kalliokoski jussi.kalliokoski at
Mon Aug 7 20:50:27 UTC 2017

On Mon, Aug 7, 2017 at 10:24 PM, Naveen Chawla <naveen.chwl at>

> However, if we are going straight from iterable to Object, I don't think
> we should be propagating the "[key, value] as an array" pattern.

Consistency is good, and especially better than for example adding new
syntax. Subjectively not a big fan of doing single pair computed key
objects either: `return { [key]: value }` vs `return [key, value]`. Arrays
also have a better set of standard library functions available which makes
preprocessing easier, for example reversing keys and values.

> It's unclean partly because it's 2 elements max and IDEs can't inherently
> show warnings if you accidentally added more, unless it has some
> intelligence about the method itself. Partly also because the arrays are
> not immediately readable unless you already know the that the arrays mean
> [key, value].

You're probably not referring to hand-writing lists of key-value pairs (in
which case you should just use an object literal to begin with), but yes,
text editors inherently don't help much with code validity to begin with,
but type systems such as flow make it pretty easy[1] to catch this sort of

/* @flow */

function objectFrom<KeyType, ValueType>(
  iterable : Iterable<[KeyType, ValueType]>
) : {
  [key : KeyType]: ValueType
} {
  const object : { [key : KeyType]: ValueType } = {};

  for (const [key, value] of iterable) {
    object[key] = value;

  return object;

objectFrom([["key", 2], [null, "value"], [1, 3]]) // <- all good
objectFrom([["key", "value", "other"]]) // <- ERROR: Tuple arity mismatch.
This tuple has 3 elements and cannot flow to the 2 elements of...
objectFrom([1,2,3,4,5].map(x => [x, x])) // <- all good
objectFrom([1,2,3,4,5].map(x => Array(x))) // <- // <- ERROR: Tuple arity

IMO it's generally a good idea to use stronger correctness guarantees than
editor syntax highlighting / validation anyway.

Regarding `Map.from(...)`, not sure how that would be useful since the map
constructor already accepts an iterator. Maybe when passing to something
that expects a function, but then adding arity (for example a mapper
function) becomes a hazard. The partial application proposal might help
with this tho: ``.

I'd be happy to see something like `Object.from(iterable)` and maybe even
`Map.from(iterable)` in the core library - simple, generic and common. Not
so convinced about the mapper functions - if an engine doesn't bother
optimizing away the extra allocation in `Object.from(` I don't
see why it would bother optimizing `Object.from(x, fn)` either. Please
correct me if and how I'm wrong though.

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

More information about the es-discuss mailing list