eternalthinker
eternalthinker

Reputation: 542

Javascript - find the index corresponding to an array key

Suppose there is a JavaScript array

myArray = {
    "key1" : value1
    ...
    "keyn" : valuen
} 

My question is, can I find the integer index corresponding to, say, "key1" ?

I need both the value and the its integer position in the array!

Upvotes: 0

Views: 1097

Answers (3)

Joe
Joe

Reputation: 82654

@Slaks is correct, but maybe you can fudge it:

for(var key in myArray) {
    var sudoIndex = +key.match(/\d+/g)[0],
        value = myArray[key];
    // do stuff
}

This assumes your keys are numbered like in your example.

Upvotes: 0

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100205

For getting value you can do:

console.log(myArray.key1);

Upvotes: 0

SLaks
SLaks

Reputation: 888223

No.
That is an object, not an array.

Object keys are unordered.

Upvotes: 5

Related Questions