简体   繁体   中英

Nodejs if else alternative

What alternative can I use instead of if condition? I have to write a 10 to 15 of if conditions and inside them we might have other if conditions. So I was wondering if there is any alternative so the code looks better? Something like case switches.

  if (sns.Trigger.Namespace == "AWS/ApiGateway") {
    if (dimensionName('ApiId') && dimensionName('Stage')) {
        var sns_DimensionsValue = dimensionValue('ApiId') + '_' + dimensionValue('Stage')
    } else if (dimensionName('ApiName') &&  dimensionName('Stage')) {
        var sns_DimensionsValue =  dimensionValue('ApiName') + '_' +  dimensionValue('Stage') 
    } else if (dimensionName('ApiId')) {
        var sns_DimensionsValue =  dimensionValue('ApiId')    
    } else if (dimensionName('ApiName')) {
        var sns_DimensionsValue =  dimensionValue('ApiName')    
    }
  }   
  
  if (sns.Trigger.Namespace == "AWS/S3") {
      var sns_DimensionsValue = dimensionValue('BucketName') + '_' + dimensionValue('StorageType')
  }  
   
  #
  if AWS/Logs
  if AWS/Lambda

Basically I have to check if the JSON data has certain keys vs some other keys in every namespace and then construct a variable. This JSON data is from AWS Cloudwatch event. dimensionName function queries the JSON data to see if name we pass exists in json.. dimensionValue returns the value of the key from JSON data.

You can use switch instead: https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Statements/switch

You can use it like this:

var myVar = myFunc(); // Get some value

switch(myVar) { // Test value possibilities
  case "hello":
    console.log("Say hello"); // Your code for "hello" case here
  break;

  case "Bye":
    console.log("Say bye"); // Your code for "bye" case here
  break;
}

Notes:

  • Switch is useful to test many variable state
  • If you have less than 5 statements, if/else is better
  • More than 5, use switch instead of if/else
  • By "better" I mean faster and less resource intensive

Edit:

In your case the problem is most certainly the operating logic. If you want to check key presence in JSON, you can maybe iterate over your JSON like this:

Object.keys(myJson).forEach((key) => {
  switch (key) {
    case "key1": // "key1" is in json
      // Code here for "key1" presence
    break;

    // etc...
  }
});

Note:

Since the number of control flow statements is very small in your case, if-else would be fine on its own, or you can use switch statements

If you want to go for something different, you could use arrays like this

each nested array contains say [[obj.a, obj.b]] that corresponds to if (obj.a && obj.b)`, we can loop through this array and then filter out undefined (in the case where the object property doesn't exist)

In the following example the first condition is [obj.a, obj.c], which fails as the property c does not exist in obj and it will resolve to undefined, and the next condition is [obj.a, obj.b] which passes as both of them are valid in obj and will return the values joined by _

 const obj = { a: 'al', b: 'bl' } const params = [[obj.a, obj.c], [obj.a, obj.b], [obj.b]]; let result; for (let i = 0; i < params.length; i++) { const x = params[i]; const value = x.filter(x => x.= undefined).length == x?length. x:join('_'); null, if (value) { // condition passes; no need to continue the loop result = value; break. } } console,log('Final variable value is -> '; result);

Note: a better solution would be to use switch , but this is just one of the possible alternatives to if-else

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM