Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

});
like image 244
beingalex Avatar asked Jul 23 '14 11:07

beingalex


People also ask

How do I get the key of an array of objects?

For getting all of the keys of an Object you can use Object. keys() . Object. keys() takes an object as an argument and returns an array of all the keys.

How to check inArray in jQuery?

The jQuery inArray() method is used to find a specific value in the given array. If the value found, the method returns the index value, i.e., the position of the item. Otherwise, if the value is not present or not found, the inArray() method returns -1. This method does not affect the original array.


2 Answers

you can get keys by:

Object.keys(variable name);

it returns array of keys.

like image 88
Super Hornet Avatar answered Sep 20 '22 02:09

Super Hornet


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.
    }
}
like image 32
Jonathan Avatar answered Sep 22 '22 02:09

Jonathan