ShoeLace1291
ShoeLace1291

Reputation: 4698

How can I use forEach to set dynamic variables in JavaScript and jQuery?

I am writing a jQuery plugin. There is an object of options that I want to loop through to set regular variables with. It would basically set a variable that would be the index of the object item. I want to determine if any options are left blank and if they are, set the regular variable to the default value. I would usually use the following to set options to a default if they are blank:

 var defaults = {
     someVar1 : "somevar1",
      omeVar2:  "somevar2"
 };

var someVar1;
var someVar2;

function init(options, defaults){
   if(typeof options.someVar1 === 'undefined'){
      someVar1 = defaults.someVar1;
   } else {
      someVar1 = options.someVar1;
  }
   return something();
}
function something(){
   console.log(item);
});

This can be a big pain in the butt if I have a lot of options to set. How could I modify my code below to dynamically define global variables?

function init(element, options){
    $(document).ready(function(){
         $.each(options, function(index, value){
             if(typeof options.index === 'undefined'){

              }
         });
     });
 }

Upvotes: 0

Views: 528

Answers (2)

GramThanos
GramThanos

Reputation: 3622

Lets say you have an object :

var my_object = {
    item1 : 1,
    item2 : 2,
    item3 : 3,
}

var i;
for(i in my_object){
    console.log(i); 
    console.log(my_object[i]);
}
/*
    This will print in the console:
    item1
    1
    item2
    2
    item3
    3
*/

for each will not find an undefined, because undefined does not exist, unless your object is like this:

var my_object = {
    item1 : 1,
    item2 : 2,
    item3 : 3,
    item4 : undefined
}

Also :

$.each(options, function(index, value){
  // if(typeof options.index === 'undefined'){ <-- this is wrong
     if(typeof options[index]=== 'undefined'){ <-- this is correct
        // Also you have the value, why not "value === undefined" ?
     }
});

Upvotes: 1

Andrew S
Andrew S

Reputation: 136

It sounds like you might want to setup a predefined variable array then based on your index of the option read its default value

var optionDefaults = ["val1", "val2", "val3"];
function init(element, options){
    $(document).ready(function(){
         $.each(options, function(index, value){
             if(typeof options.index === 'undefined'){
                  var optiondefValue = optionDefaults[index];
                  //do whatever you want here.
              }
         });
     });
 }

Upvotes: 0

Related Questions