1

How can I add an "else" statement to the following dictionary with key/value pairs to handle any sort of ambiguity?

var inputArr = input.match(/[\d.]+/g).map(Number);
var inputAnswer = ""

inputArr.forEach(function(element, index){

var lookUp = {
    "1":"611"
    "2":"612"
    "3":"613"
    "":""
};
    inputAnswer = lookUp[element];
}
    return inputAnswer
});

As you can see, the key/value pairs are only programmed to handle "1","2","3", and "". How can I add another value to it which would return blank string ("") if it is passed any other value? Just want it to be dynamically set up to handle any sort of data. Thanks!

user7366442
  • 731
  • 2
  • 9
  • 16

1 Answers1

3

Using a simple ternary, combined with hasOwnProperty will let you do what you want.

Note: using a simple || check may not give the desired results, as it will return '' if falsey value is set in the lookUp object. For a demo of why / how this may not do what you expect, see this fiddle

var inputArr = input.match(/[\d.]+/g).map(Number);
var inputAnswer = ""

inputArr.forEach(function(element, index) {
    var lookUp = {
        "1":"611"
        "2":"612"
        "3":"613"
        "":""
    };

    // If a defined value exists, return it, otherwise ''
    inputAnswer = ( lookUp.hasOwnProperty(element) ) ? lookUp[element] : '';
}
    return inputAnswer
});
random_user_name
  • 25,694
  • 7
  • 76
  • 115
  • 1
    Thank you sir for using the `hasOwnProperty` and the explanation why to use it, it's rare to see it in the wild nowadays :) – cyr_x Jul 31 '17 at 21:54