A TC39 proposal to add iterator-like methods to objects

Currently in ECMAScript, iterating over & manipulating Objects is also a bit tedious at the moment in ECMAScript. We need to use Object.keys(obj), Object.values(obj), or Object.entries(obj) and chain them. So if we want to create a new object from an previous one with the same keys, only a modification of its values, we need to write:

Object.fromEntries(Object.entries(object).map(([key, value]) => [key, transformation(value)])

This is a bit verbose.

Manipulating objects could be made simpler.

Proposal GitHub - Ayc0/proposal-object-iterator: A TC39 proposal to add iterator-like methods to objects

Adding new methods to Object.prototype is unlikely to be web compatiable. For example a website could be doing:

if (config.forEach) {
  // assumes config is array
} else {
  // assumes config is plain object
}

This isn't only the case for Object, it happens with Array too, e.g. the Array.prototype.group proposal turned out to not be web compatible, so was changed to Object.groupBy (static method). Because almost all objects inherit from Object.prototype the risk factor is increased.

1 Like

what about using Object.map?

But then it'll conflict with MooTools :confused:

Edit: after checking the library, it should be fine

Something like this has been proposed before and withdrawn:

Looks like the history section doesn't include the Feb 2020 notes that seems to have caused the withdrawal, but you can find that here (I didn't read myself but there should be more info - click the link for the full notes rather than relying on the preview here):

3 Likes

I'm gonna drop the iterator from this proposal, and move the functions to Object.<function>. After checking MooTools, it should be compliant

This will avoid the issue with the prototype chain

@senocular tbh, I was hesitant about adding the paragraph about making object iterables (I mentioned "could be split in 2 proposals"), and same about modifying the prototype.
I didn't fully think about all issues it could introduce, from the 'map' in …, or also the fact that it'd add for instance .map on WeakSet which we don’t want at all.

But adding Object.map(object, fn) that would be sort of an alias for Object.fromEntries(Object.entries(object).map(([key, value]) => [key, fn(value)])) shouldn’t have the issues that were mentioned in the previous meeting note, right?

As mentioned in my previous message, I checked MooTools. And according to their docs, their Object.map behaves exactly like the one I'm proposing in this proposal (and same for the other methods).

The proposal was updated:

  • I dropped the mention of making object iterable,
  • I updated the functions to make them static methods on Object instead of functions on the prototype,
  • I added a new section in the QnA