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

JavascriptDictionary

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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);
}

Solution 2 - Javascript

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.

Solution 3 - Javascript

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

Solution 4 - Javascript

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);
            }
        }
    }
}

Solution 5 - Javascript

Simply use Object.keys():

var driversCounter = {
                      "one": 1,
                      "two": 2,
                      "three": 3,
                      "four": 4,
                      "five": 5
                     }
console.log(Object.keys(driversCounter));

Solution 6 - Javascript

With a modern JavaScript engine you can use Object.keys(driversCounter).

Solution 7 - Javascript

For new browsers: Object.keys( MY_DICTIONARY ) will return an array of keys. Else you may want to go the old school way:

var keys = []
for(var key in dic) keys.push( key );

Solution 8 - Javascript

As others have said, you could use Object.keys(), but who cares about older browsers, right?

Well, I do.

Try this. array_keys from PHPJS ports PHP's handy array_keys function, so it can be used in JavaScript.

At a glance, it uses Object.keys if supported, but it handles the case where it isn't very easily. It even includes filtering the keys based on values you might be looking for (optional) and a toggle for whether or not to use strict comparison === versus typecasting comparison == (optional).

Solution 9 - Javascript

If you can use jQuery then

var keys = [];
$.each(driversCounter, function(key, value) {
    keys.push(key);
});

console.log(JSON.stringify(keys));

Here follows the answer:

["one", "two", "three", "four", "five"]

And this way you wouldn't have to worry if the browser supports the Object.keys method or not.

Solution 10 - Javascript

A different approach would be to using multi-dimensional arrays:

var driversCounter = [    ["one", 1], 
    ["two", 2], 
    ["three", 3], 
    ["four", 4], 
    ["five", 5]
]

and access the value by driverCounter[k][j], where j=0,1 in the case.
Add it in a drop down list by:

var dd = document.getElementById('your_dropdown_element');
for(i=0;i<driversCounter.length-1;i++)
{
    dd.options.add(opt);
    opt.text = driversCounter[i][0];
    opt.value = driversCounter[i][1];
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFreeViceView Question on Stackoverflow
Solution 1 - JavascriptalexView Answer on Stackoverflow
Solution 2 - JavascriptVisioNView Answer on Stackoverflow
Solution 3 - JavascriptJosephView Answer on Stackoverflow
Solution 4 - JavascriptAadit M ShahView Answer on Stackoverflow
Solution 5 - JavascriptAmil SajeevView Answer on Stackoverflow
Solution 6 - JavascriptThiefMasterView Answer on Stackoverflow
Solution 7 - JavascriptParth ThakkarView Answer on Stackoverflow
Solution 8 - JavascriptNiet the Dark AbsolView Answer on Stackoverflow
Solution 9 - JavascriptDarius KucinskasView Answer on Stackoverflow
Solution 10 - JavascriptshirazView Answer on Stackoverflow