Is there an elegant way to access the first property of an object...
- where you don't know the name of your properties
- without using a loop like
for .. in
or jQuery's$.each
For example, I need to access foo1
object without knowing the name of foo1:
var example = {
foo1: { /* stuff1 */},
foo2: { /* stuff2 */},
foo3: { /* stuff3 */}
};
There isn't a "first" property. Object keys are unordered.
If you loop over them with for
(var foo in bar)
you will get them in some order, but it may change in future (especially if you add or remove other keys).Solution with lodash library:
but there is no guarantee of the object properties internal storage order because it depends on javascript VM implementation.
You can also do
Object.values(example)[0]
.Any reason not to do this?
No. An object literal, as defined by MDC is:
Therefore an object literal is not an array, and you can only access the properties using their explicit name or a
for
loop using thein
keyword.Use an array instead of an object (square brackets).
Note that you lose the 'foo' identifiers. But you could add a name property to the contained objects: