161

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
FreeVice
  • 2,567
  • 6
  • 21
  • 28

10 Answers10

261

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);
}
alex
  • 479,566
  • 201
  • 878
  • 984
74

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
VisioN
  • 143,310
  • 32
  • 282
  • 281
21

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 ":"
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Joseph
  • 117,725
  • 30
  • 181
  • 234
10

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);
            }
        }
    }
}
Aadit M Shah
  • 72,912
  • 30
  • 168
  • 299
8

Simply use Object.keys():

var driversCounter = {
                      "one": 1,
                      "two": 2,
                      "three": 3,
                      "four": 4,
                      "five": 5
                     }
console.log(Object.keys(driversCounter));
eregon
  • 1,486
  • 14
  • 15
Amil Sajeev
  • 270
  • 2
  • 9
5

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
4

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 );
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Parth Thakkar
  • 5,427
  • 3
  • 25
  • 34
2

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).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
0

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Darius Kucinskas
  • 10,193
  • 12
  • 57
  • 79
-5

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];
}
Guilherme David da Costa
  • 2,318
  • 4
  • 32
  • 46
shiraz
  • 188
  • 3
  • 10