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?
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:Plus, there's a plethora of other useful functions that are worth perusing.
you can use the
each
function:it has several nice shortcuts/tricks: check the gory details here
I use something like this function I created...
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.
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
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 -
Using jQuery, easiest way to get array of keys from object is following:
In your case, it will return this array:
["alfa", "beta"]