5

Possible Duplicate:
how to fetch array keys with jQuery?

php built-in function array_keys(), equivalent in jquery is there any built in function in jquery similar to that of php array_keys(),.

please suggest

2
  • 1
    Check this out: stackoverflow.com/questions/1254227/… Commented Oct 9, 2012 at 14:34
  • 1
    Btw: Arrays in Javascript can only have numerical keys, there's no such thing as an associative array. It only can be simulated by an object (but has flaws) Commented Oct 9, 2012 at 14:39

5 Answers 5

4

You will have to define your own function to get the same functionality. Try this:

function arrayKeys(input) {
    var output = new Array();
    var counter = 0;
    for (i in input) {
        output[counter++] = i;
    } 
    return output; 
}

arrayKeys({"one":1, "two":2, "three":3}); // returns ["one","two","three"]
Sign up to request clarification or add additional context in comments.

Comments

3

No there isn't anything specific in jQuery for this. There is a javascript method but it is not widely supported yet Object.keys() so people don't use it for generic projects. Best thing i could think of is

var keys = $.map(your_object, function(value, key) {
  return key;
});

1 Comment

This is the best answer, but Object.keys() is widely supported now, including IE9+ developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
3

You don't need jQuery or any other library for this -- it's a standard part of Javascript.

for(var key in myObject) {
    alert(key);
}

That should be sufficient for you to loop through the object. But if you want to actually get the keys into their own array (ie turn it into a genuine clone of the php function), then it's fairly trivial to extend the above:

function array_keys(myObject) {
    output = [];
    for(var key in myObject) {
        output.push(key);
    }
    return output;
}

Note, there are caveats with using the for(..in..) technique for objects that have properties or methods that you don't want to include (eg core system properties), but for a simple object that you've created yourself or from a JSON string, it's ideal.

(For more info on the caveats, see http://yuiblog.com/blog/2006/09/26/for-in-intrigue/)

Comments

1

Take a look at PHPJS, a project that aims to reproduce many PHP functions in vanilla JavaScript with minimal dependencies. In your case, you want array_keys.

Comments

1

In JavaScript there's no such thing like associative arrays. Objects (object literals) handle similar cases.

var keys = [], i = 0;    
for( keys[ i++ ] in yourObject );

And now keys contains all yourObject property names (keys).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.