nbroeking nbroeking - 4 months ago 8
Javascript Question

How to iterate (keys, values) in javascript?

I have a dictionary that has the format of

dictionary = {0: {object}, 1:{object}, 2:{object}}


How can I iterate through this dictionary by doing something like

for((key,value) in dictionary){
//Do stuff where key would be 0 and value would be the object
}

Answer

No, its not possible with JavaScript objects.

You should either iterate with for..in, or Object.keys, like this

for (var key in dictionary) {
    if (dictionary.hasOwnProperty(key) {
        console.log(key, dictionary[key]);
    }
}

Note: The if condition above is necessary, only if you want to iterate the properties which are dictionary object's very own. Because for..in will iterate through all the inherited enumerable properties.

Or

Object.keys(dictionary).forEach(function(currentKey) {
    console.log(key, dictionary[key]);
});

In ECMA Script 2015, you can use Map objects and iterate them with Map.prototype.entries. Quoting example from that 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 iterate 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);
}

Output

[ '0', 'foo' ]
[ 1, 'bar' ]
[ {}, 'baz' ]