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 e
console.log( Object.keys( {'a':1,'b':2} ) );
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"]
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 -
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.
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
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.