1

I have an object like the following:

var RevenueCodes = {
            41020: "Addendum",
            41040: "Cardiology Assessment",
            41060: "Chiropractic Assessment",
            41290: "Neurology File Review - CAT",
            41240: "Neurology Assessment"
            }

How can I find the number if I search for “Addendum” using JavaScript?

hvgotcodes
  • 118,147
  • 33
  • 203
  • 236
Karim Ali
  • 2,243
  • 6
  • 23
  • 31
  • possible duplicate of [Best way to find an item in a JavaScript array?](http://stackoverflow.com/questions/143847/best-way-to-find-an-item-in-a-javascript-array) – Marc B Aug 23 '11 at 16:53
  • Technically, I suppose this is valid syntax, but an object's members names shouldn't start with a number. E.g. it's not legal to reference `RevenueCodes.41020`. Of course, you can say `RevenueCodes['41020']` to get around it, but I would use an array instead. – nikc.org Aug 23 '11 at 16:57

4 Answers4

0

I would have two vars, RevenueByCode and CodeByRevenue, the former being what you have and the latter being the same except with the key/values reversed, so you can get constant time lookup at the expense of having to (possibly) set up the second variable by looping over the first.

You can do

var code;
for (var key in RevenueCodes) {
   var val = RevenueCodes[key];
   if (val === 'Addendum') code = key;
}

to get the code (you should optimize a bit) and you can also use the same loop structure to setup your other lookup, if you want to do that.

hvgotcodes
  • 118,147
  • 33
  • 203
  • 236
0
var number;
for(var key in RevenueCodes) { // iterate
    if(RevenueCodes.hasOwnProperty(key) && RevenueCodes[key] === "Addendum") {
        // if it's not a prototype property and the value is Addendum, store key
        // as number and stop the loop
        number = key;
        break;
    }
}
pimvdb
  • 151,816
  • 78
  • 307
  • 352
0

You can use for...in to enumerate object properties.

var RevenueCodes = {
  41020: "Addendum",
  41040: "Cardiology Assessment",
  41060: "Chiropractic Assessment",
  41290: "Neurology File Review - CAT",
  41240: "Neurology Assessment"
};
for (var propertyName in RevenueCodes) {
  if (RevenueCodes[propertyName] === "Addendum") {
    console.log("property name: %s", propertyName);
    break;
  }
}
Jed Fox
  • 2,979
  • 5
  • 28
  • 38
canon
  • 40,609
  • 10
  • 73
  • 97
0

Javascript has direct way of doing this. You need to loop through all the keys, compare the values and then choose the right one.. If you want to do this repeatedly, you need to build the reverse map once and use it...

Teja Kantamneni
  • 17,402
  • 12
  • 56
  • 86