Reputation: 23
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
}
Upvotes: 0
Views: 762
Reputation: 30607
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);
Upvotes: 7
Reputation: 63587
Assuming that the keys are important and, unlike the other answers suggest, they are actually needed in the form you've put in your question, put your keys/codes in an array instead using an object for each group. Then you can use filter
on the array to pluck out the correct key based on the code provided:
var regionCodes = {
codes: [{
key: 4, code: '00501'
}, {
key: 4, code: '00544'
}, {
key: 4, code: '06390'
}, {
key: 2, code: '96161'
}, {
key: 2, code: '96162'
}],
getKey: function (value) {
var arr = this.codes.filter(function (el) {
return el.code === value;
});
return arr.length ? arr[0].key : 9;
}
};
Upvotes: 3