How can I get a collection of keys in a JavaScript dictionary? [duplicate]
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?
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);
}
One option is using Object.keys()
:
Object.keys(driversCounter)
It works fine for modern browsers (however, Internet Explorer supports it starting from version 9 only).
To add compatible support you can copy the code snippet provided in MDN.
To loop through the "dictionary" (we call it object in JavaScript), use a for in
loop:
for(var key in driversCounter) {
if(driversCounter.hasOwnProperty(key)) {
// key = keys, left of the ":"
// driversCounter[key] = value, right of the ":"
}
}