EN
JavaScript - what is the most efficient way to get first item from associative array?
1
answers
0
points
What is the most efficient way to get the first item from an associative array in JavaScript?
Actually I need to get, just the first key of a large associative array.
1 answer
0
points
Since associative arrays in JavaScript are objects, there isn't really a first or last element.
You can hope to acquire the order that the elements were saved by the parser and there's no guarantee for consistency.
However, if you want the first key to come up, here is an example function:
// ONLINE-RUNNER:browser;
function getKey(object) {
for (var property in object) {
return property;
}
}
// Usage example
var associativeArray = {
key1: 'value1',
key2: 'value2',
};
console.log(getKey(associativeArray));
or if you want to avoid inheritance properties:
// ONLINE-RUNNER:browser;
function getKey(object) {
for (var property in object) {
if (object.propertyIsEnumerable(property)) {
return property;
}
}
}
// Usage example:
var associativeArray = {
key1: 'value1',
key2: 'value2',
};
console.log(getKey(associativeArray));
0 comments
Add comment