HiGonz HiGonz - 1 month ago 5x
Javascript Question

Evaluate boolean expression from a variable in JavaScript

I have some Variables that have like a key word and then an identifier and I'm trying to evaluate this expression.


$day = today; //Assume it is Monday
$.each(responseAdvertiser, function(index, value) {
var hasMonday = value.hasMonday; //TRUE OR FALSE
var hasTuesday = value.hasTuesday; //TRUE OR FALSE

//Whar I'm trying to do:
var has="has";
var img="img";
var txt="txt";
var day = $day.toLowerCase(); //monday
var hasDay = has+day; //hasmonday

if (hasDay == true){ // TRYING TO EVALUATE THIS
var dayImg= day+img; //mondayimg
var dayTxt = day+txt; //mondaytxt

var todayImg = value.dayImg;
var todayTxt = value.dayTxt;
// I know how to make this work in PHP using variable variables, like
// $x = hello
// $hello = buddy
// echo $$x #PRINTS buddy

I am trying to evaluate hasmonday, but since I'm using the variable "hasDay" which is just a string named "hasmonday" it doesn't really evaluate the way I need to.

Hope I made myself clear, if not, comment and I'll try to explain it better. Thanks in advance.


To access a property by name, use the brackets notation.

So for your example, you could get the boolean value by

var hasDay = "hasMonday";
var b = value[hasDay]; // equivalent to 'var b = value.hasMonday;'
if (b) {
    // code here