beingalex beingalex - 5 months ago 15
jQuery Question

How to get array key name using jQuery?

I have an array like this:

var myArray = new Array();

myArray['foo'] = {
Obj: {
key: value
}
};
myArray['bar'] = {
Obj: {
key: value
}
};


When I do
console.log(myArray)
I just get empty
[ ]
. And when I try to iterate the array using jQuery's
each
the function doesn't run.

How can I get the 'foo' and 'bar' parts of the array?

Example code:

console.log(myArray); // [ ]

jQuery.each(myArray, function(key, obj) {
console.log(key); // should be 'foo' following by 'bar'
});


In addition, why does this work:

jQuery.each(myArray[foo], function(obj, values) {

// Why does this work if there are no associative arrays in JS?

});

Answer

You need to define it as an object if you want to access it like that:

var myObj= {};

myObj.foo = ...;
myObj.bar = ...;

Now you can access the properties like myObj["bar"] or myObj.bar

Note:
To loop through all the properties it's wise to add an additional check. This is to prevent you from looping through inherited properties.

for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
        // Do stuff.
    }
}