Get element of JS object with an index

JavascriptObject

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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

myobj[Object.keys(myobj)[0]];

Solution 2 - Javascript

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]];

Solution 3 - Javascript

myobj = {"A":["Abe"], "B":["Bob"]}

Object.keys(myobj)[0];	//return the key name at index 0
Object.values(myobj)[0]  //return the key values at index 0

Solution 4 - Javascript

var myobj = {"A":["Abe"], "B":["Bob"]};

var keysArray = Object.keys(myobj);

var valuesArray = Object.keys(myobj).map(function(k) {

   return String(myobj[k]);

});

var mydata = valuesArray[keysArray.indexOf("A")]; // Abe

Solution 5 - Javascript

myobj.A

------- or ----------

myobj['A']

will get you 'B'

Solution 6 - Javascript

$.each(myobj, function(index, value) { 
    console.log(myobj[index]);
});

Solution 7 - Javascript

If you want a specific order, then you must use an array, not an object. Objects do not have a defined order.

For example, using an array, you could do this:

var myobj = [{"A":["B"]}, {"B": ["C"]}];
var firstItem = myobj[0];

Then, you can use myobj[0] to get the first object in the array.

Or, depending upon what you're trying to do:

var myobj = [{key: "A", val:["B"]}, {key: "B",  val:["C"]}];
var firstKey = myobj[0].key;   // "A"
var firstValue = myobj[0].val; // "["B"]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChapmIndustriesView Question on Stackoverflow
Solution 1 - JavascriptCatWithGlassesView Answer on Stackoverflow
Solution 2 - JavascriptAlnitakView Answer on Stackoverflow
Solution 3 - JavascriptDennis PaixaoView Answer on Stackoverflow
Solution 4 - JavascriptdosetView Answer on Stackoverflow
Solution 5 - JavascriptJeffpowrsView Answer on Stackoverflow
Solution 6 - JavascriptFahem IdirView Answer on Stackoverflow
Solution 7 - Javascriptjfriend00View Answer on Stackoverflow