Consider:
var object = {
foo: {},
bar: {},
baz: {}
}
How would I do this:
var first = object[0];
console.log(first);
Obviously, that doesn’t work because the first index is named foo
,
not 0
.
console.log(object['foo']);
works, but I don’t know it’s named foo. It could be named anything. I just want the first.
There is no way to get the first element, seeing as "hashes" (objects) in JavaScript have unordered properties. Your best bet is to store the keys in an array:
Then use that to get the proper value:
I had the same problem yesterday. I solved it like this:
Not the most elegant solution, and I am pretty sure that it may yield different results in different browsers (i.e. the specs says that enumeration is not required to enumerate the properties in the same order as they were defined). However, I only had a single property in my object so that was a non-issue. I just needed the first key.
Using underscore you can use _.pairs to get the first object entry as a key value pair as follows:
Then the key would be available with a further
[0]
subscript, the value with[1]
Based on CMS answer. I don't get the value directly, instead I take the key at its index and use this to get the value:
Just for fun this works in JS 1.8.5
This matches the same order that you would see doing
To get the first key of your object