Reputation: 33
After parsing values through Ajax request (GET), I need to replace them with other values -> i.e. multiple postal codes corresponding to the same country code ( "1991,1282,6456" : "Idaho", etc. )
This is what I've done so far :
$mapCodes = {
'1991': 'Idaho',
'1282': 'Idaho',
'5555': 'Kentucky',
'7777': 'Kentucky '
}
var region = value.groupid.replace(/7777|5555|1282|1991/, function(matched) {
return $mapCodes[matched];
});
console.log(region);
This works, but I'd rather avoid setting my $mapCodes variable as a long list of values repeated.
I need something like and array of array to whitch make the match (and then the replacement)
$mapCodes = {
'1991,1282' : 'Idaho',
'7777,5555' : 'Kentycky'
}
Upvotes: 1
Views: 68
Reputation: 3487
imudin07 already answered correctly and with easier-to-read code, but just out of curiosity, here's another possibility, using modern JS syntax and array methods map, reduce and some.
var mapCodes = {
"Idaho": ['1991', '1282'],
"Kentucky": ['5555', '7777']
};
var input = "1991 7777 1282 9999";
var result = input.split(' ').map((inputCode) => (
Object.keys(mapCodes).reduce((matchingState, curState) => (
matchingState || (mapCodes[curState].some((code) => code === inputCode) ? curState : false)
), false) || inputCode
)).join(' ');
console.log(result);
Upvotes: 0
Reputation: 2852
You need to use array which elements are $mapCodes's keys:
{
"Idaho":[1991,1282]
}
Here is the demo:
$mapCodes = {
"Idaho":['1991','1282'],
"Kentucky":['5555','7777']
}
var test="1991 7777 1282"; /// input string
var region = test; // result string
for(let key in $mapCodes){
let a =$mapCodes[key];
for(let i=0; i<a.length; i++) {
region = region.replace(a[i],key);
}
}
console.log(region);
Upvotes: 2