Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simplify multiple if statements javascript?

I have multiple conditions to check. I have to add icons based on the conditions, Then I need to change the background color based on some other set of conditions. I am using if statement. This is my code.

JSON:

{
  "date": "2017-05-12",  
  "a": false,
  "b": true,
  "c": true,  
  "d": false,
  "status": "active"
}

Javascript:

 if (date != -1) {
  //do something
  if (a) {
    //Add icon a
  }
  if (b) {
    //Add icon b
  }
  if (c) {
    //Add icon c
  }
  if (d) {
    //Add icon d
  }
}

if(status == "active"){
  //Background Green
}
else if (status == "onhold"){
  //Background Yellow
}
else if (status == "inactive"){
  //Background Red
}
else{
  //Backgeound Grey
}

How do I simplify it?

like image 534
Aasim Hussain Khan Avatar asked Jun 13 '26 04:06

Aasim Hussain Khan


2 Answers

The first half of you code looks fine. For the second half of your code you should make use of a switch statement. These replace the if-else statements you are using and decide what to do when certain "cases" occur. For example:

switch(status) {
    case 'active':
        //background green
        break;
    case 'onhold':
        //background yellow
        break;
    case 'inactive':
        //background red
        break;
    default:
        //background grey
        break;
}
like image 172
Roars Avatar answered Jun 14 '26 18:06

Roars


My idea is:

var icons = {
    a: 'a.png',
    b: 'b.png',
    c: 'c.png',
    d: 'd.png',
}

if (date != -1) {
    Object.keys(icons).forEach(function(key) {
        if (data[key]) {
            //Add icon icons[key]
        }
    });
}

var statusColors = {
    active: 'Green',
    onhold: 'Yellow',
    inactive: 'Grey',
}

//Background statusColors[status]
like image 40
zswang Avatar answered Jun 14 '26 17:06

zswang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!