ECMAScript Proposal, specs, and reference implementation for
Spec drafted by @ljharb.
Designated TC39 reviewers: @wycats @littledan @rwaldron
- TC39 meeting notes
- https://esdiscuss.org/topic/object-values-and-or-object-foreach -> https://esdiscuss.org/topic/iteration-was-re-object-values-and-or-object-foreach
It is a very common use case to need the own values of an object - for example, when using an object as a hash filter. Many libraries have a “values” function: lodash/underscore, jQuery, Backbone, etc.
It is also useful to obtain an array of key/value pairs (what the spec calls “entries”) from an object, for the purposes of iteration or serialization. With the advent of the
Map constructor accepting an iterable of
entries, and its associated
entries iterator (
WeakMap also accepts iterable
entries in its constructor), it becomes very compelling to want to quickly convert a plain object to a
Map, via passing an array of
We already have the precedent of
Object.keys returning an array of own keys, and matched triplets of
entries iterators on
Array. As such, per discussions on es-discuss and in at least one previous TC39 meeting, this proposal seeks to add
Object.entries to ECMAScript. Like
Object.keys, they would return arrays. Their ordering would match
Object.keys ordering precisely, such that the indices of all three resulting arrays would reflect the same key, value, or entry on the object.
Iterators or Arrays?
Object.keys is paramount in this proposal‘s opinion. A follow-on proposal for an iterator, however, could likely be
Reflect.ownEntries, which would complete the triplet with
Reflect.ownKeys, providing an array of both string-valued and symbol-valued properties. However, this proposal is focused on
Object.entries, and the existence of either the
Reflect forms should not preclude the existence of the other. In addition, the current precedent for returning iterators from
entries currently only applies to methods on prototypes - and in addition, “
Object is special” seems to be something many accept. Also, arrays are themselves iterable already.