JavaScript – First key from associative array

First element of an array - JavascriptWorking 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]

It's only fair to share...Buffer this pageShare on Facebook0Tweet about this on TwitterShare on Google+0Share on LinkedIn0Share on Reddit0Pin on Pinterest0Email this to someone
About

Just a guy with strong interest in PHP and Web technologies

Tagged with: , , ,
One comment on “JavaScript – First key from associative array
  1. Kamran Saeed says:

    Great tip! Worked perfectly for me. Thanks!!!

Leave a Reply

Your email address will not be published. Required fields are marked *

*