pedalpete
pedalpete

Reputation: 21536

getting variable/object elements and values in javascript

I'm not sure if I'm using the correct terminology, so please correct me if I'm not.

I've got a javascript variable which holds a group of values like this

var my_variables = {
             first_var: 'starting',
             second_var: 2,
             third_var: 'continue',
             forth_var: 'end'
}

Now I'm trying to get these variables in my script, but I don't want to have to check for each one. Right now i'm doing this

if(my_variables.first_var!=null){
   query=query+'&first_var='+my_variables.first_var;
}
if(my_variables.second_var!=null){
   query=query+'&second_var='+my_variables.second_var;
}...

I'm hoping there is a simple way to recursively go through the object, but I haven't been able to find how to do that. Something like

 
foreach(my_variables.??? as varName){
    query=query+'&'+varName+'='+my_variables.varName;
}

Upvotes: 0

Views: 737

Answers (2)

Dan
Dan

Reputation: 11069

for (var varName in my_variables) { query=query+'&'+varName+'='+my_variables[varName]; }

for (... in ...) is how you write this kind of loop in Javascript. Also use square brackets instead of a period when the field name is a value instead of the actual identifier, like here. Incidentally, I'd also suggest using window.encodeURIComponent if your values might contain arbitrary text.

Upvotes: 1

NVRAM
NVRAM

Reputation: 7137

Try this:

for(var key in my_variables)
  query += '&'+key+'='+encodeURIComponent(my_variables[key]);

Upvotes: 2

Related Questions