Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php function array_keys equivalent in jquery [duplicate]

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

like image 431
Manojkumar Avatar asked Oct 09 '12 14:10

Manojkumar


4 Answers

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"]
like image 143
Khior Avatar answered Nov 08 '22 22:11

Khior


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;
});
like image 32
Lee Avatar answered Nov 08 '22 21:11

Lee


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

like image 3
SDC Avatar answered Nov 08 '22 21:11

SDC


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.

like image 1
Niet the Dark Absol Avatar answered Nov 08 '22 22:11

Niet the Dark Absol