abz
abz

Reputation: 31

Want multiple match in if else statement

problem: I want to match muliple statement without breaking for just one.

code:

        if(options === "opt1"){
            obj['opt1Users'].push(userName);
            obj['opt1Count'] = resSurvey[0].opt1Count + 1;
        }
        else if(options  === "opt2"){
            obj['opt2Users'].push(userName);
            obj['opt2Count'] = resSurvey[0].opt2Count + 1;
        }
        else if(options === "opt3"){
            obj['opt3Users'].push(userName);
            obj['opt3Count'] = resSurvey[0].opt3Count + 1;
        }else if(options  === "opt4"){
            obj['opt4Users'].push(userName);
            obj['opt4Count'] =resSurvey[0].opt4Count + 1;
        }

Upvotes: 0

Views: 151

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074178

Using dynamic property access via brackets notation, you could have a single if and create the property names with string concatenation:

if (options === "opt1" || options === "opt2" || options === "opt3" || options === "opt4") {
    obj[options + "Users"].push(userName);
    obj[options + "Count"] = resSurvey[0][options + "Count"] + 1;
}

(If you already know that options will have one of those four values, you could do away with the if entirely.)

That said, you might consider updating the structure of obj so you didn't need concatenation. For instance, if obj had properties for opt1, opt2, etc. that were objects, those objects could have count and users properties:

const entry = obj[options];
if (entry) { // Minor assumption here, that `options` matches our `opt1` etc. properties but not some *other* property of `obj`.
    entry.users.push(userName);
    entry.count = resSurvey[0][options + "Count"] + 1;
}

Upvotes: 2

Related Questions