1

I have this object:

var navArray = {
  '#item1' : 0,
  '#item2' : 1,
  '#item3' : 2,
  '#item4' : 3,
  '#item5' : 4,
  '#item6' : 5
}

The ident var in the code below is a number and I need to find out which property it corresponds to in the array...so if ident is 1 I want to get #item2 back..

How do I do this?

var navArray = {
  '#item1' : 0,
  '#item2' : 1,
  '#item3' : 2,
  '#item4' : 3,
  '#item5' : 4,
  '#item6' : 5
}
if(typeof(ident) === "number") {
    for(i in navArray) {
    }
}
Brad Christie
  • 100,477
  • 16
  • 156
  • 200
Mike Rifgin
  • 10,409
  • 21
  • 75
  • 111
  • 1
    navArray[i] should do it – Kris Ivanov Feb 07 '11 at 16:51
  • 2
    Your `navArray` isn't an array at all. Is there something wrong with using `navArray = ['#item1', '#item2', '#item3', ...]`? Then you'd be able to index into it directly: `navArray[ident]`. – Roatin Marth Feb 07 '11 at 17:07
  • @K Ivanov: your solution assumes that data is sorted. elduderino, is this object always the same so that sorting is a safe assumption? – Jordan Feb 07 '11 at 17:08
  • It is important to note that this example is _not_ an array, but an object/map/associative-array (whatever you want to call it) - you can tell by the {} syntax - arrays use []. Your variable name is confusing.. If you want to iterate an array, see http://stackoverflow.com/a/3010848/251185 – thetoolman May 23 '12 at 02:18

1 Answers1

7

This should work:

var ident = 1,
    target = null;
for (var key in navArray) {
    if (navArray.hasOwnProperty(key)) { 
        if (navArray[key] === ident) {
            target = key;
            break;
        }
    }
}

alert (target); // "#item2"
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • In which case will this: `navArray.hasOwnProperty(key)` not return true?? – yankee Feb 07 '11 at 17:30
  • 1
    @yankee: as per Crockford: "Be aware that members that are added to the prototype of the object will be included in the enumeration. It is wise to program defensively by using the hasOwnProperty method to distinguish the true members of the object." – ThatGuy Jul 29 '11 at 16:23