0

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;
}

2 Answers 2

2

Try this:

for(var key in my_variables)
  query += '&'+key+'='+encodeURIComponent(my_variables[key]);
Sign up to request clarification or add additional context in comments.

1 Comment

WOW! you must have an easy button or something! Thanks Carter. that worked Perfectly as far as I can tell.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.