p1xelarchitect
p1xelarchitect

Reputation: 289

How to convert a string to variable name

I'm loading several external JSON files and want to check if they have been successfully cached before the the next screen is displayed. My strategy is to check the name of the array to see if it an object. My code works perfectly when I check only a single array and hard code the array name into my function. My question is: how can i make this dynamic?

not dynamic: (this works)

$("document").ready(){
    checkJSON("nav_items"); 
}

function checkJSON(){

   if(typeof nav_items == "object"){
       // success...
   }

}

dynamic: (this doesn't work)

$("document").ready(){
    checkJSON("nav_items"); 
    checkJSON("foo_items"); 
    checkJSON("bar_items"); 
}

function checkJSON(item){

   if(typeof item == "object"){
       // success...
   }

}

here is the a larger context of my code:

var loadAttempts = 0;  
var reloadTimer = false;  



$("document").ready(){
    checkJSON("nav_items"); 
}



function checkJSON(item){

loadAttempts++;

//if nav_items exists
if(typeof nav_items == "object"){

        //if a timer is running, kill it
        if(reloadTimer != false){
        clearInterval(reloadTimer);
        reloadTimer = false;
    } 
    console.log("found!!");
    console.log(nav_items[1]);
    loadAttempts = 0; //reset

            // load next screen....                   

} 

//if nav_items does not yet exist, try 5 times, then give up!
else {
            //set a timer
    if(reloadTimer == false){
        reloadTimer = setInterval(function(){checkJSON(nav_items)},300);
        console.log(item + " not found. Attempts: " + loadAttempts );
    }
            else {
        if(loadAttempts <= 5){
            console.log(item + " not found. Attempts: " + loadAttempts          );
        } else {
            clearInterval(reloadTimer);
            reloadTimer = false;
            console.log("Giving up on " + item + "!!");
        }
    }
}

}

Upvotes: 0

Views: 75

Answers (2)

Balachandran
Balachandran

Reputation: 9637

you have to pass the object ...not string .declare the variable and and assign the json value

checkJSON(nav_items); 
 checkJSON(foo_items); 
 checkJSON(bar_items);

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337580

Depending on the scope of the arrays you should be able to access them via window[]:

$("document").ready(function() {
    checkJSON("nav_items"); 
});

function checkJSON(item) {
   if (typeof window[item] == "object") {
       alert(item + ' is an object');
   }
}

Example fiddle

Upvotes: 2

Related Questions