Get the key from an associative array

Hi, I am currently retrieving an array with .each

$.each(messages, function(key,message){ doStuff(); });

But the key is the index of the array, not the associative key.

How can I get it easily?

thank

+5
source share
3 answers
var data = {
    val1 : 'text1',
    val2 : 'text2',
    val3 : 'text3'
};
$.each(data, function(key, value) {
    alert( "The key is '" + key + "' and the value is '" + value + "'" );
});

See Demo

+9
source

There are no "associative arrays" in JavaScript. It has arrays:

[1, 2, 3, 4, 5]

and objects:

{a: 1, b: 2, c: 3, d: 4, e: 5}

There are no "keys" in the array; they have indexes that are counted starting at 0.

Arrays are accessed using [], and objects can be accessed using []or ..

Example:

var array = [1,2,3];
array[1] = 4;
console.log(array); // [1,4,3]

var obj = {};
obj.test = 16;
obj['123'] = 24;
console.log(obj); // {test: 16, 123: 24}

int, . , .

var array = [1,2,3];
array['test'] = 4; // this doesn't set a value in the array
console.log(array); // [1,2,3]
console.log(array.test); // 4

jQuery $.each . $.each key , .

$.each([1, 2, 3, 4, 5], function(key, value){
    console.log(key); // logs 0 1 2 3 4
});

$.each({a: 1, b: 2, c: 3, d: 4, e: 5}, function(key, value){
    console.log(key); // logs 'a' 'b' 'c' 'd' 'e'
});
+19

JavaScript " ", PHP, . , . , , , key - , , , , , .

, , , for -loop , $.each.

0

All Articles