TL; dr
- In ECMAScript 5, this is not possible.
- In ECMAScript 2015, this is possible with
Map s. - In ECMAScript 2017, it will be easily accessible.
ECMAScript 5:
No, this is not possible with objects.
You must either for..in with for..in or Object.keys , like this
for (var key in dictionary) { // check if the property/key is defined in the object itself, not in parent if (dictionary.hasOwnProperty(key)) { console.log(key, dictionary[key]); } }
Note: the if condition above is only necessary if you want to iterate over properties that are property of the dictionary object. Because for..in will for..in over all inherited enumerated properties.
Or
Object.keys(dictionary).forEach(function(key) { console.log(key, dictionary[key]); });
ECMAScript 2015
In ECMAScript 2015, you can use Map objects and repeat them using Map.prototype.entries . Quoting an example from this page,
var myMap = new Map(); myMap.set("0", "foo"); myMap.set(1, "bar"); myMap.set({}, "baz"); var mapIter = myMap.entries(); console.log(mapIter.next().value); // ["0", "foo"] console.log(mapIter.next().value); // [1, "bar"] console.log(mapIter.next().value); // [Object, "baz"]
Or for..of with for..of like this
'use strict'; var myMap = new Map(); myMap.set("0", "foo"); myMap.set(1, "bar"); myMap.set({}, "baz"); for (const entry of myMap.entries()) { console.log(entry); }
Exit
[ '0', 'foo' ] [ 1, 'bar' ] [ {}, 'baz' ]
Or
for (const [key, value] of myMap.entries()) { console.log(key, value); }
Exit
0 foo 1 bar {} baz
ECMAScript 2017
ECMAScript 2017 will introduce the new Object.entries feature. You can use this to iterate over the object as you like.
'use strict'; const object = {'a': 1, 'b': 2, 'c' : 3}; for (const [key, value] of Object.entries(object)) { console.log(key, value); }
Exit
a 1 b 2 c 3