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'm just empty [ ]. And when I try to iterate through an array using jQuery each, the function does not start.

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

Code example:

console.log(myArray); // [ ]

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

Also, why does this work:

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

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

});
+4
source share
6 answers

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

var myObj= {};

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

Now you can access properties such as myObj["bar"]ormyObj.bar

:
, . , .

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

:

Object.keys(variable name);

.

+2

- , . , push

 myArray.push('someValue');

( < index):

 myArray.push('someValue1');
 myArray.push('someValue1');
 myArray[0] = 'new someValue1';

, Object, / :

myArray.foo = '1';
myArray['bar'] = '2';

, . , . :

var myObj = {};

, . Javascript ( )?

+2
var myArray = {};

myArray['foo'] = {  'key': 'value'  }

myArray['bar'] ={  'key': 'value'  }

console.log(myArray)

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

   console.log(obj, values)

});

0

Array of Objects :

var getKeys = function(obj) {
  if (!(typeof obj == "object")) return [];
  var keys = [];
  for (var key in obj) if (obj != null && hasOwnProperty.call(obj, key)) keys.push(key);
  return keys;
};

getKeys (myArray) .

_.keys(myArray). .

0

// $.each() , .

var myArray = {};
myArray['alfa'] = 0;
myArray['beta'] = 1;
$.each(myArray, function(key, value) {
      alert(key);
});

. http://api.jquery.com/jQuery.each/.

0

All Articles