I'm trying to get the following to return the appropriate key but keep getting only 9. Help and 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 also tried (and failed) with the variation that 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
}
Best How To :
You have identical keys {4:,4:,4:,2:,2:}
in your object. Try making the keys unique or change your approach like in Andys answer.
Otherwise, it will only work if the value happens to be of the first key in the 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
with 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);