beingalex beingalex - 1 year ago 175
Javascript Question

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
I just get
[ ]
. And when I try to iterate the array using jQuery's
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 Source

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

var myObj= {}; = ...; = ...;

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

To loop through all the properties you need an additional check. This is to prevent you from looping through inherited properties.

for (var key in object) {
    if (object.hasOwnProperty(key)) {
        // Do stuff.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download