javascript - Clean way to test many conditions of different values? -
so , want test many conditions, different values... right bunch of if,else statements...
but looks ugly im sure there must better way...
any ideas ?
im thinking maybe loops or putting vars in array, cant figure out how..
thx!
var dataobject = {} if (newstate.playerid){ dataobject["filter[player_id]"] = newstate.playerid }else{ dataobject["filter[player_id]"] = this.state.playerid } if (newstate.pagelimit){ dataobject ["page[limit]"] = newstate.pagelimit }else{ dataobject["page[limit]"] = this.state.pagelimit } if (newstate.timefrom){ dataobject["time[from]"] = newstate.timefrom }else{ dataobject["time[from]"] = this.state.timefrom } if (newstate.timeto){ dataobject["time[to]"] = newstate.timeto }else{ dataobject["time[to]"] = this.state.timeto } if (newstate.gameid){ dataobject["filter[game_id]"] = newstate.gameid }else{ dataobject["filter[game_id]"] = this.state.gameid } if (newstate.customerid){ dataobject["filter[customer_id]"] = newstate.customerid }else{ dataobject["filter[customer_id]"] = this.state.customerid } if (newstate.currency){ dataobject["filter[currency]"] = newstate.currency }else{ dataobject["filter[currency]"] = this.state.currency } if (newstate.variant){ dataobject["filter[locale]"] = newstate.locale }else{ dataobject["filter[locale]"] = this.state.locale } if (newstate.variant){ dataobject["filter[demo]"] = newstate.demo }else{ dataobject["filter[demo]"] = this.state.demo }
reducing condition
first, can use javascript's ||
operator , change:
if (newstate.playerid){ dataobject["filter[player_id]"] = newstate.playerid }else{ dataobject["filter[player_id]"] = this.state.playerid }
to reduced:
dataobject["filter[player_id]"] = newstate.playerid || this.state.playerid;
dry code
you can use array of properties:
var propertylist = ["playerid", "pagelimit", "timefrom" /* etc. */]
because object properties can referenced using square brackets can loop through them this:
propertylist.foreach(function(property){ dataobject[property] = newstate[property] || this.state[property] });
disclaimer: solution not taking account embedded objects (like "filter") , slight variations in naming schemes (like "player_id" vs "playerid").
three solutions occur me:
use consistent naming conventions
in other words indataobject
build have same naming patternstate
object.use helper function
convert names in loop using kind of consistent pattern changesplayerid
player_id
when kinds of changes need done. (this still not work if plan use "filter", "time" or "page".use objects/arrays (as in @ssube's solution)
use array or object translate property names between objects. won't give example - @ssube has done already.
Comments
Post a Comment