How to use if statement inside JSON?

How to use if statement inside JSON Here is the code: ......................................... ..............................................

var config = [ { "name" : "SiteTitle", "bgcolor" : "", "color" : "", "position" : "TL", "text" : "step1", "time" : 5000 }, { "name" : "Jawal", "bgcolor" : "", "color" : "", "text" : "step2", "position" : "BL", "time" : 5000 }, { "name" : "Password", "bgcolor" : "", "color" : "", "text" : "step3", "position" : "TL", "time" : 5000 } ], //define if steps should change automatically autoplay = false, //timeout for the step showtime, //current step of the tour step = 0, //total number of steps total_steps = config.length; 

This is a necessary result:

  var config = [ if(page==true) { { "name" : "SiteTitle", "bgcolor" : "", "color" : "", "position" : "TL", "text" : "step1", "time" : 5000 }, { "name" : "Jawal", "bgcolor" : "", "color" : "", "text" : "step2", "position" : "BL", "time" : 5000 } } else { { "name" : "Password", "bgcolor" : "", "color" : "", "text" : "step3", "position" : "TL", "time" : 5000 } } ], //define if steps should change automatically autoplay = false, //timeout for the step showtime, //current step of the tour step = 0, //total number of steps total_steps = config.length; 

Actually this path is wrong and makes a JavaScript syntax error.

+4
source share
3 answers

This is plain JavaScript, not JSON. Move the if out of bounds:

 if (page) { var config = [ { "name" : "SiteTitle", "bgcolor" : "", "color" : "", "position" : "TL", "text" : "step1", "time" : 5000 }, { "name" : "Jawal", "bgcolor" : "", "color" : "", "text" : "step2", "position" : "BL", "time" : 5000 } ]; } else { var config = [ { "name" : "Password", "bgcolor" : "", "color" : "", "text" : "step3", "position" : "TL", "time" : 5000 } ]; } 
+2
source

or perhaps this:

  var config = (page == true) ? [ { "name" : "SiteTitle", "bgcolor" : "", "color" : "", "position" : "TL", "text" : "step1", "time" : 5000 }, { "name" : "Jawal", "bgcolor" : "", "color" : "", "text" : "step2", "position" : "BL", "time" : 5000 } : { "name" : "Password", "bgcolor" : "", "color" : "", "text" : "step3", "position" : "TL", "time" : 5000 } ]; 
0
source

You can also do this (not to say that this is the best way, but it is different and may be useful in some scenarios)

 let config = []; if (page) { config.push({ "name" : "SiteTitle", "bgcolor" : "", "color" : "", "position" : "TL", "text" : "step1", "time" : 5000 }); config.push({ "name" : "Jawal", "bgcolor" : "", "color" : "", "text" : "step2", "position" : "BL", "time" : 5000 }); } else { config.push({ "name" : "Password", "bgcolor" : "", "color" : "", "text" : "step3", "position" : "TL", "time" : 5000 }); } 
0
source

All Articles