0

In an object such as:

var a = {"a":"value1", "b": "value2", "c":"value3"};

How do I get the value of the second element in the object without knowing the element's name? Same for variable n3 and so on...

3 Answers 3

5

Object properties do not have a defined order, as per the object specification.

If you're looking to come back and fix this project some day, you could do something stupid like...

var theThirdForAnyValueOfThird = a[Object.keys(a)[2]];
Sign up to request clarification or add additional context in comments.

Comments

2

According to the language spec (see sections 4.3.3 and 12.6.4), the properties of an object are not ordered, so there is no "second element". This is different from the numeric properties (subscripts) of an array.

The best approach, if you want to associate a particular order to the keys, is to store the keys themselves in an array and access them by subscript (not using for...in).

All major browser implementations will iterate the properties in the order in which they were added. While this is ill-advised, you might be able to get away with:

a[Object.keys(a)[1]]

to get the "second element" value. Just be aware that this relies on an accident of implementation and is not guaranteed to work everywhere. Basically, it's an accident waiting to happen if you do this.

6 Comments

Have references for the ordering (or lack of) for different browser implementations?
@pst - See the section "for loop order" in John Resig's article JavaScript in Chrome.
I found this first in google: code.google.com/p/v8/issues/detail?id=164, which points out that this is NOT the case where a key can be parsed into a 32 bit integer
Interesting (+1) .. never considered that an insertion-ordered implementation was common, but wish there were more references. (Some people still have to make things "work" in IE6 and other ancient browsers. Also, IE10 uses a new script engine? :-/)
BTW, there is no order to Array properties either (Arrays are objects). Order is created by accessing them using an index. Using for..in will return them out of order in some browsers in some cases.
|
0

You can't and would need to switch to an array. As workaround, I have been doing weird things like this:

var a = [{"a":"value1"}, {"b": "value2"}, {"c":"value3"}];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.