44

Good afternoon. I have an array with some keys, and values in them. I then need to fetch the array keys and not the data in them. I want to do this with jQuery. I know for example that PHP has a function called array_keys(); which takes the array as a parameter and gives you an array back with each key in each index.

This is what I came up with, and it works... the only problem is that it seems so unefficent;

var foo = [];
foo['alfa'] = "first item";
foo['beta'] = "second item";

for (var key in foo) {
    console.log(key);
}

This will output;

alfa
beta

But is there any predefined function for this, as in PHP or any other more effective way of getting this?

6 Answers 6

68

you can use the each function:

var a = {};
a['alfa'] = 0;
a['beta'] = 1;
$.each(a, function(key, value) {
      alert(key)
});

it has several nice shortcuts/tricks: check the gory details here

Sign up to request clarification or add additional context in comments.

3 Comments

and what does $.each() use internally for objects?! This method will be slower because the use of a callback function will increase the length of the scope chain and therefore take longer to resolve the reference to a's properties
Don't forget to use curved brackets instead of squared brackets to define the array!
console.log(key) would work better for a long list etc
52

Using jQuery, easiest way to get array of keys from object is following:

$.map(obj, function(element,index) {return index})

In your case, it will return this array: ["alfa", "beta"]

1 Comment

One minor difference from Object.keys is that JQuery version (tested with JQuery v1.6.2 and v1.8.2) returns array keys (indices) as integers as opposed to Object.keys returning those as strings. Though this wont be an issue in 99.999% of the cases...
37

In modern browsers, the easiest way to get the keys of an array is Object.keys(). For example:

console.log( Object.keys( {'a':1,'b':2} ) );

1 Comment

This is only in javascript 1.8.5+ For browser support see the table at bottom of page here: developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…
8

Don't Reinvent the Wheel, Use Underscore

I know the OP specifically mentioned jQuery but I wanted to put an answer here to introduce people to the helpful Underscore library if they are not aware of it already.

By leveraging the keys method in the Underscore library, you can simply do the following:

_.keys(foo)  #=> ["alfa", "beta"]

Plus, there's a plethora of other useful functions that are worth perusing.

Comments

5

Use an object (key/value pairs, the nearest JavaScript has to an associative array) for this and not the array object. Other than that, I believe that is the most elegant way

var foo = {};
foo['alfa'] = "first item";
foo['beta'] = "second item";

for (var key in foo) {
        console.log(key);
}

Note: JavaScript doesn't guarantee any particular order for the properties. So you cannot expect the property that was defined first to appear first, it might come last.

EDIT:

In response to your comment, I believe that this article best sums up the cases for why arrays in JavaScript should not be used in this fashion -

1 Comment

Thanks for the note, luckily it won't matter for me in this particular case. :) But just one question, why is it better to have it as an object (associative array)?
0

I use something like this function I created...

Object.getKeys = function(obj, add) {
    if(obj === undefined || obj === null) {
        return undefined;
    }
    var keys = [];
    if(add !== undefined) {
        keys = jQuery.merge(keys, add);
    }
    for(key in obj) {
        if(obj.hasOwnProperty(key)) {
                keys.push(key);
        }
    }
    return keys;
};

I think you could set obj to self or something better in the first test. It seems sometimes I'm checking if it's empty too so I did it that way. Also I don't think {} is Object.* or at least there's a problem finding the function getKeys on the Object that way. Maybe you're suppose to put prototype first, but that seems to cause a conflict with GreenSock etc.

1 Comment

Even here it's done something like that. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… I thought one was suppose to just use keys() but it was not fully implimented yet so I rolled my own as I often do.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.