user7366442
user7366442

Reputation: 751

Adding an else Statement to a Javascript dictionary key value pairs?

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!

Upvotes: 1

Views: 386

Answers (1)

random_user_name
random_user_name

Reputation: 26170

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

Upvotes: 3

Related Questions