I have a dictionary that has the format of
JavaScript
x
2
1
dictionary = {0: {object}, 1:{object}, 2:{object}}
2
How can I iterate through this dictionary by doing something like
JavaScript
1
4
1
for ((key, value) in dictionary) {
2
//Do stuff where key would be 0 and value would be the object
3
}
4
Advertisement
Answer
tl;dr
- In ECMAScript 2017, just call
Object.entries(yourObj)
. - In ECMAScript 2015, it is possible with
Map
s. - In ECMAScript 5, it is not possible.
ECMAScript 2017
ECMAScript 2017 introduced a new Object.entries
function. You can use this to iterate the object as you wanted.
JavaScript
1
8
1
'use strict';
2
3
const object = {'a': 1, 'b': 2, 'c' : 3};
4
5
for (const [key, value] of Object.entries(object)) {
6
console.log(key, value);
7
}
8
Output
JavaScript
1
4
1
a 1
2
b 2
3
c 3
4
ECMAScript 2015
In ECMAScript 2015, there is not Object.entries
but you can use Map
objects instead and iterate over them with Map.prototype.entries
. Quoting the example from that page,
JavaScript
1
11
11
1
var myMap = new Map();
2
myMap.set("0", "foo");
3
myMap.set(1, "bar");
4
myMap.set({}, "baz");
5
6
var mapIter = myMap.entries();
7
8
console.log(mapIter.next().value); // ["0", "foo"]
9
console.log(mapIter.next().value); // [1, "bar"]
10
console.log(mapIter.next().value); // [Object, "baz"]
11
Or iterate with for..of
, like this
JavaScript
1
11
11
1
'use strict';
2
3
var myMap = new Map();
4
myMap.set("0", "foo");
5
myMap.set(1, "bar");
6
myMap.set({}, "baz");
7
8
for (const entry of myMap.entries()) {
9
console.log(entry);
10
}
11
Output
JavaScript
1
4
1
[ '0', 'foo' ]
2
[ 1, 'bar' ]
3
[ {}, 'baz' ]
4
Or
JavaScript
1
4
1
for (const [key, value] of myMap.entries()) {
2
console.log(key, value);
3
}
4
Output
JavaScript
1
4
1
0 foo
2
1 bar
3
{} baz
4
ECMAScript 5:
No, it’s not possible with objects.
You should either iterate with for..in
, or Object.keys
, like this
JavaScript
1
7
1
for (var key in dictionary) {
2
// check if the property/key is defined in the object itself, not in parent
3
if (dictionary.hasOwnProperty(key)) {
4
console.log(key, dictionary[key]);
5
}
6
}
7
Note: The if
condition above is necessary only if you want to iterate over the properties which are the dictionary
object’s very own. Because for..in
will iterate through all the inherited enumerable properties.
Or
JavaScript
1
4
1
Object.keys(dictionary).forEach(function(key) {
2
console.log(key, dictionary[key]);
3
});
4