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…
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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:
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.