Javascript function in associative array not working -


i'm trying following return appropriate key keep getting 9. , thank you.

var strzip = "96161";  var regioncodes = { 4: '00501',     4: '00544',     4: '06390',     2: '96161',     2: '96162', getkey: function(value){     for(var key in this){         if(this[key] == value){             return key;         }     }     return 9; // default 9 if not found     } };  var zipkey = regioncodes.getkey(strzip); 

i've tried (and failed) variation reads:

getkey: function(value){     for(var key in this){         if( this.hasownproperty( key) ) {             if(this[key] === value){                 return key;             }         }     }     return 9; // default 9 if not found } 

you have identical keys {4:,4:,4:,2:,2:} in object. try making keys unique or change approach in andys answer.

otherwise, work if value happens of first key in object

var strzip = "96161";    var regioncodes = {  1: '00501',      2: '00544',      3: '06390',      4: '96161',      5: '96162',  getkey: function(value){      for(var key in this){          if(this[key] == value){              return key;          }      }      return 9; // default 9 if not found      }  };    var zipkey = regioncodes.getkey(strzip);  console.log(zipkey);

or use key -> array indexof() like

var strzip = "961261";    var regioncodes = {  4: ['00501', '00544',  '06390'],  2: ['96161', '96162'],  getkey: function(value){      for(var key in this){          if(typeof(this[key]) != 'function' && this[key].indexof(value) > -1){              return key;          }      }      return 9; // default 9 if not found      }  };    var zipkey = regioncodes.getkey(strzip);  console.log(zipkey);


Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - .htaccess mod_rewrite for dynamic url which has domain names -

Website Login Issue developed in magento -