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
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"]
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;
});
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/)
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With