How can I get a collection of keys in a JavaScript dictionary?

FreeVice picture FreeVice · May 18, 2012 · Viewed 208k times · Source

I have a dictionary:

var driversCounter = {
    "one":   1,
    "two":   2,
    "three": 3,
    "four":  4,
    "five":  5
}

Now, I need to show it in a dropdownlist. How can I get the collection of keys in my dictionary?

Answer

alex picture alex · May 18, 2012

Use Object.keys() or shim it in older browsers...

const keys = Object.keys(driversCounter);

If you wanted values, there is Object.values() and if you want key and value, you can use Object.entries(), often paired with Array.prototype.forEach() like this...

Object.entries(driversCounter).forEach(([key, value]) => {
   console.log(key, value);
});

Alternatively, considering your use case, maybe this will do it...

var selectBox, option, prop;

selectBox = document.getElementById("drivers");

for (prop in driversCounter) {
   option = document.createElement("option");
   option.textContent = prop;
   option.value = driversCounter[prop];
   selectBox.add(option);
}