Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

Can Dictionary have duplicate keys in JavaScript?

No, JavaScript objects cannot have duplicate keys. The keys must all be unique.

Can HashMap have duplicate keys in JavaScript?

It is not allowed to have duplicated keys in a HashMap. You have to use another structure.


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 ":"
    }
}

This will work in all JavaScript implementations:

var keys = [];

for (var key in driversCounter) {
    if (driversCounter.hasOwnProperty(key)) {
        keys.push(key);
    }
}

Like others mentioned before you may use Object.keys, but it may not work in older engines. So you can use the following monkey patch:

if (!Object.keys) {
    Object.keys = function (object) {
        var keys = [];

        for (var key in object) {
            if (object.hasOwnProperty(key)) {
                keys.push(key);
            }
        }
    }
}