JavaScript – First key from associative array
Working with arrays is very beneficial for every developer in every language. But in different languages some operations are done differently. Very good example is retrieving first key from an associative array in JavaScript. In PHP you could use “foreach“, “list“, “array_pop“, “array_slice“, etc. But in JavaScript we don’t have all that functions so we have to stick to what the language offers us. Here is the actual tip:
[cc escaped=”true” lang=”javascript”]function getFirstKey( data ) {
for (elem in data )
return elem;
}
var myArray = {a: 1, b: 2, c: 3, d: 4};
// This will give us “a”
var firstKey = getFirstKey(myArray);
// This will give us “1”
var firstValue = myArray[firstKey];
[/cc]
Great tip! Worked perfectly for me. Thanks!!!