1

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'
}
5
  • 1
    Please fix the snippet I made to reflect the actual code you have - there is not value.groupid defined. I also added a quote and a comma to the invalid object Commented Dec 20, 2018 at 9:09
  • What exactly are you worried about? Is the issue that you want to write non-repetitive code, or are you thinking about performance? Commented Dec 20, 2018 at 9:09
  • 2
    Turn them around: "Kentucky": [7777,5555] and look them up using value search Commented Dec 20, 2018 at 9:12
  • You can use array as a key in object. Commented Dec 20, 2018 at 9:21
  • why dont use filter? Commented Dec 20, 2018 at 9:31

2 Answers 2

2

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);

Sign up to request clarification or add additional context in comments.

1 Comment

This work perfectly indeed. Thanks you all and apologise for my mistakes in the post, is my first time :D
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.