Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get element of JS object with an index

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".

like image 487
ChapmIndustries Avatar asked Feb 10 '13 20:02

ChapmIndustries


People also ask

How do you find the value of an object with an index?

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.

How do you find the value of an object in an array?

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.


2 Answers

I know it's a late answer, but I think this is what OP asked for.

myobj[Object.keys(myobj)[0]]; 
like image 110
CatWithGlasses Avatar answered Sep 30 '22 19:09

CatWithGlasses


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]]; 
like image 36
Alnitak Avatar answered Sep 30 '22 19:09

Alnitak