Ok so let's say that I have my object
myobj = {"A":["Abe"], "B":["Bob"]}
and I want to get the first element out of it. As in I want it to return Abe
which has an index of A
. How can I do something along the lines of myobj[0]
and get out "Abe".
To get a value of an object by index:Use the Object. keys() method to get an array of the object's keys. Use bracket notation to get the key at the specific index. Access the object by the key to get the corresponding value.
Answer: Use the find() Method You can simply use the find() method to find an object by a property value in an array of objects in JavaScript. The find() method returns the first element in the given array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.
I know it's a late answer, but I think this is what OP asked for.
myobj[Object.keys(myobj)[0]];
JS objects have no defined order, they are (by definition) an unsorted set of key-value pairs.
If by "first" you mean "first in lexicographical order", you can however use:
var sortedKeys = Object.keys(myobj).sort();
and then use:
var first = myobj[sortedKeys[0]];
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