Le 15/03/2014 01:32, Brandon Benvie a écrit :
On 3/14/2014 5:16 PM, Mark Volkmann wrote:
Does ES6 add any new ways to iterate over the values in an object?
I've done a lot of searching, but haven't seen anything.
I'm wondering if there is something more elegant than this:

Object.keys(myObj).forEach(function (key) {
  let obj = myObj[key];
  // do something with obj
});

Not built in, but ES6 does provide a better story for this using generators and for-of:

```js
// using a generator function
function* entries(obj) {
  for (let key of Object.keys(obj)) {
    yield [key, obj[key]];
  }
}

// an alternative version using a generator expression
function entries(obj) {
  return (for (key of Object.keys(obj)) [key, obj[key]]);
}

for (let [key, value] of entries(myObj)) {
  // do something with key|value
}
```
Currently, there is no default Object.prototype.@@iterator, so for-of'ing over an object throws a TypeError which isn't really a useful default. No having a default @@iterator also makes that Map({a:1, b:2}) throws which is unfortunate.

Should what you just wrote be made the default Object.prototype.@@iterator? It is compatible with the signature the Map constructor expects too.

David
_______________________________________________
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss

Reply via email to