Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the key of an associative array

I'm currently fetching an array with .each:

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

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

How can I get it easily?

like image 466
Asai Lopze Avatar asked Jun 07 '12 17:06

Asai Lopze


People also ask

How do you find the key in an associative array?

Answer: Use the PHP array_keys() function You can use the PHP array_keys() function to get all the keys out of an associative array.

What is key in associative array?

An associative array is an array with string keys rather than numeric keys. Associative arrays are dynamic objects that the user redefines as needed. When you assign values ​​to keys in a variable of type Array, the array is transformed into an object, and it loses the attributes and methods of Array.

How do you find the key of an array?

use array_keys() to get an array of all the unique keys. Note that an array with named keys like your $arr can also be accessed with numeric indexes, like $arr[0] .

What is array_keys () used for?

The array_keys() is a built-in function in PHP and is used to return either all the keys of and array or the subset of the keys. Parameters: The function takes three parameters out of which one is mandatory and other two are optional.


2 Answers

JavaScript doesn't have "associative arrays". It has arrays:

[1, 2, 3, 4, 5]

And objects:

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

Array's don't have "keys". They have indices, which 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}

If you try to access an array using a string as a key instead of an int, that may cause problems. You would be setting a property of the array and not a value.

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's $.each works with both of these. In the callback for $.each, the first parameter, key, is either the object's key, or the array's index.

$.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'
});
like image 198
Rocket Hazmat Avatar answered Nov 03 '22 21:11

Rocket Hazmat


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

See the Demo

like image 22
Nishu Tayal Avatar answered Nov 03 '22 22:11

Nishu Tayal