Is there an elegant way to access the first property of an object...
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 */} };
To get a value of an object by index, call the Object. values() method to get an array of the object's values and use bracket notation to access the value at the specific index, e.g. Object. values(obj)[1] . Copied!
Javascript array is a variable that holds multiple values at a time. The first and last elements are accessed using an index and the first value is accessed using index 0 and the last element can be accessed through length property which has one more value than the highest array index.
var obj = { first: 'someVal' }; obj[Object.keys(obj)[0]]; //returns 'someVal'
Using this you can access also other properties by indexes. Be aware tho! Object.keys
return order is not guaranteed as per ECMAScript however unofficially it is by all major browsers implementations, please read https://stackoverflow.com/a/23202095 for details on this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With