Getting a list of associative array keys

JavascriptArrays

Javascript Problem Overview


I have an associative array in JavaScript:

var dictionary = {
    "cats": [1,2,3,4,5],
    "dogs": [6,7,8,9,10]
};

How do I get this dictionary's keys? I.e., I want

var keys = ["cats", "dogs"];

Just to get the terminology correct - there is no such thing as an 'associative array' in JavaScript - this is technically just an object and it is the object keys we want.

Javascript Solutions


Solution 1 - Javascript

Try this:

var keys = [];
for (var key in dictionary) {
  if (dictionary.hasOwnProperty(key)) {
    keys.push(key);
  }
}

hasOwnProperty is needed because it's possible to insert keys into the prototype object of dictionary. But you typically don't want those keys included in your list.

For example, if you do this:

Object.prototype.c = 3;
var dictionary = {a: 1, b: 2};

and then do a for...in loop over dictionary, you'll get a and b, but you'll also get c.

Solution 2 - Javascript

for (var key in dictionary) {
  // Do something with key
}

It's the for..in statement.

Solution 3 - Javascript

You can use: Object.keys(obj)

Example:

var dictionary = {
  "cats": [1, 2, 37, 38, 40, 32, 33, 35, 39, 36],
  "dogs": [4, 5, 6, 3, 2]
};

// Get the keys
var keys = Object.keys(dictionary);

console.log(keys);

See reference below for browser support. It is supported in Firefox 4.20, Chrome 5, and Internet Explorer 9. Object.keys() contains a code snippet that you can add if Object.keys() is not supported in your browser.

Solution 4 - Javascript

Just a quick note. Be wary of using for..in if you use a library (jQuery, Prototype, etc.), as most of them add methods to created Objects (including dictionaries).

This will mean that when you loop over them, method names will appear as keys. If you are using a library, look at the documentation and look for an enumerable section, where you will find the right methods for iteration of your objects.

Solution 5 - Javascript

Simple jQuery way:

This is what I use:

DictionaryObj being the JavaScript dictionary object you want to go through. And value, key of course being the names of them in the dictionary.

$.each(DictionaryObj, function (key, value) {
    $("#storeDuplicationList")
        .append($("<li></li>")
        .attr("value", key)
        .text(value));
});

Solution 6 - Javascript

I am currently using Rob de la Cruz's reply:

Object.keys(obj)

And in a file loaded early on I have some lines of code borrowed from elsewhere on the Internet which cover the case of old versions of script interpreters that do not have Object.keys built in.

if (!Object.keys) {
    Object.keys = function(object) {
        var keys = [];
        for (var o in object) {
            if (object.hasOwnProperty(o)) {
                keys.push(o);
            }
        }
        return keys;
    };
}

I think this is the best of both worlds for large projects: simple modern code and backwards compatible support for old versions of browsers, etc.

Effectively it puts JW's solution into the function when Rob de la Cruz's Object.keys(obj) is not natively available.

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
QuestionSimon_WeaverView Question on Stackoverflow
Solution 1 - JavascriptJW.View Answer on Stackoverflow
Solution 2 - JavascriptwombletonView Answer on Stackoverflow
Solution 3 - JavascriptRob de la CruzView Answer on Stackoverflow
Solution 4 - JavascriptJesseView Answer on Stackoverflow
Solution 5 - JavascriptExzileView Answer on Stackoverflow
Solution 6 - JavascriptIvanView Answer on Stackoverflow