3

I have a JSON object

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

And I can return values using 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 I can return the value using its position? e.g. obj.1

Caleb Bramwell
  • 1,332
  • 2
  • 12
  • 24
  • 2
    JavaScript objects don't have order. – Ram Aug 04 '14 at 22:04
  • Run a for/in loop and assign the values to an Array. The problem is some Browsers will alphabetize the Object properties by name, so you might not get consistent results. – StackSlave Aug 04 '14 at 22:05
  • @PHPglue even though ECMAscript specifically defines no order, many browsers do use an ordering such as "insert order". I never heard of one that does it alphabetically, though. – Alnitak Aug 04 '14 at 22:07
  • My Objects are almost never in the order I make them when looking in Firebug. – StackSlave Aug 04 '14 at 22:08
  • Are you perhaps a PHP programmer, where key/value arrays also have numeric indices? – Alnitak Aug 04 '14 at 22:11

3 Answers3

5

I'll assume you think of Object.keys() or a for..in loop

You can't rely on its position, because depending on the browser implementation, object keys are sorted in lexicographic order OR not, ecma5 does not force to do either way.

axelduch
  • 10,769
  • 2
  • 31
  • 50
  • that's understanding it - ES5 _specifically says_ that an object is an _unordered set of key/value pairs_. Any ordering you happen to get is therefore an implementation issue. – Alnitak Aug 04 '14 at 22:09
2

JSON don't have indexes, what you can do is create an array of indexes:

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

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

Ende Neu
  • 15,581
  • 5
  • 57
  • 68
  • "_and then use those keys_" ... in whatever random order `for ... in ...` dropped them there... – Alnitak Aug 04 '14 at 22:11
  • I started the answer with _"JSON don't have indexes"_, perhaps what I wrote after gives the idea that there's some ordering to it? – Ende Neu Aug 04 '14 at 22:13
  • 1
    Your answer could still give the OP the impression that the elements will end up in the array in some deterministic order. – Alnitak Aug 04 '14 at 22:14
  • So essentially there is no way to do it? – Caleb Bramwell Aug 04 '14 at 22:44
  • Alnitak comment was pretty informing: "_ES5 specifically says that an object is an unordered set of key/value pairs_" and aduch answer also: "_object keys are sorted in lexicographic order OR not, ecma5 does not force to do either way._", so no, it's not possible. – Ende Neu Aug 04 '14 at 22:46
1

Good answer here:

https://stackoverflow.com/a/11509718/1443478

var obj = { first: 'someVal' };
obj[Object.keys(obj)[0]]; //returns 'someVal'
Community
  • 1
  • 1
Brennan
  • 5,632
  • 2
  • 17
  • 24