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:

    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];

Post to Twitter Post to Yahoo Buzz Post to Delicious Post to Digg Post to Facebook Post to Google Buzz Send Gmail Post to LinkedIn Post to MySpace Post to Reddit Post to StumbleUpon Post to Technorati

Tags: , , ,

No comments yet.

Leave a Reply