3

I have a multidimensional and I want to get the first element of the 2nd dimension.

myArray[0]

is my 2nd dimension. I am not able to use

myArray[0][0]

because I don't know the key of the 2nd dimenson (key = userID). Any idea how to get the first element without knowing the key?

2 Answers 2

7

Object properties (JavaScript does not have true multidimensional or associate arrays) have no defined order, and can only be accessed via their string key.

The order of iterating over keys with a for ( in ) is implementation specific as no order is specified in the specification. For example, Chrome orders numeric keys no matter what order they are added (as an array related optimisation for V8).

If you decide you don't want to listen to me and want to live dangerously, you could get the first property according to the JavaScript implementation with var worksExceptWhenItDoesnt = myArray[Object.keys(myArray)[0]].

Sign up to request clarification or add additional context in comments.

Comments

2

Object.keys() isn't cross-browser unfortunately. To be safe, just do this:

var firstKey="";
for(firstKey in object) break;

That's it - firstKey has the firstKey value. so:

var firstKey="";
for(firstKey in myArray[0]) break;

then access via:

myArray[0][firstKey]

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.