Performing iterative operations on dictionary object?

Hi.

I am currently trying to index items in a dictionary, in which my dictionary has key and value pairs. I want to use a for loop to iterate through the items in the dictionary, however it isn’t quite clear how to do this.

I tried the below approach:

var myDict = {"myKey": 10, "myKey2": 20};

for (var i = 0; i < myDict .length; i++) {
     console.log(myDict[i]);
}

However, --ignoring the fact that using myDict.length returns null-- it returns undefined. It would make sense, as I am basically asking for a key in the dict named [“i”] instead of getting item number [i] like a traditional list.

I was hoping to not have to make a separate list for just the dictionary keys, seeing as my dictionary is rather long.

Reading around I can’t find any mentions of this issue. In addition, most of the methods to do this operation that I can find online involve calling functions that exist in java but not code.org.

Any advice is appreciated, I could very well just have overlooked something. Thanks!
Tobi

Try this

var myDict = {"myKey":10, "myKey2":20};
for (var key in myDict){
 console.log(myDict[key]);
}
2 Likes

Ah yes, thank you! This solved my issue. I am fluent in python, so I am not as great in using complicated structures for iteratives in java. I appreciate the help!

1 Like