JSON object return values โ€‹โ€‹based on position

I have a JSON object

var obj = {"firstName":"John", "lastName":"Doe"}

      

And I can return values โ€‹โ€‹with obj.firstName

etc. But in my case, I might not know the name of the header, but I know its position. Is there a way to return a value using its position? egobj.1

+3


source to share


3 answers


I guess you think about Object.keys()

or cyclefor..in



You cannot rely on your position, because depending on the browser implementation, the object keys are sorted in lexicographic order OR not, ecma5 does not enforce it anyway.

+5


source


JSON has no indices, what you can do is create an array of indices:

var indexes = []
for(var key in obj) {
  indexes.push(key);
}

      



And then use those keys to access the JSON elements, note that it for...in

returns keys in random order.

+2


source


Good answer here:

fooobar.com/questions/20793 / ...

var obj = { first: 'someVal' };
obj[Object.keys(obj)[0]]; //returns 'someVal'

      

+1


source







All Articles