How can I get a collection of keys in a JavaScript 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.