What is the most efficient way to get the first item from an associative array in JavaScript?
You can avoid having to create a function by referencing the first entry returned from Object.keys()
:
var firstKey = Object.keys(data)[0];
For the first entry from a sorted key list, simply add a call to the .sort()
method:
var firstKey = Object.keys(data).sort()[0];
There isn't really a first or last element in associative arrays (i.e. objects). The only order you can hope to acquire is the order the elements were saved by the parser -- and no guarantees for consistency with that.
But, if you want the first to come up, the classic manner might actually be a bit easier:
function getKey(data) { for (var prop in data) return prop;}
Want to avoid inheritance properties?
function getKey(data) { for (var prop in data) if (data.propertyIsEnumerable(prop)) return prop;}
In addition to Jonathan's solution, we can also extend the default array functionality:
Array.prototype.getKey = function() { for (var prop in this) if (this.propertyIsEnumerable(prop)) return prop;}