String as variable/array name

Hi there,

Been looking around the old internet for an answer to this problem for about 3 hours now and I can’t seem to find anything suitable.

Here’s the deal. I want to have a series of arrays that update on click. There are 9 sets of checkboxes, each within a parent div with a unique id. The id name is the same as the array name. When a checkbox is clicked my script checks the parent div’s id, then modifies the correct array. At the moment I’m using a series of switch statements to discern the array from the id, like so:


var sausages = [], mash = [], gravy = []; //etc..
$(':checkbox').click(function){
  switch($(this).parent().attr('id')){
    case 'sausages':
      sausages.push($(this).val());
      break;
    case 'mash':
      mash.push($(this).val());
      break;
    case 'gravy':
      gravy.push($(this).val());
      break;
    //etc..
  }
});

What I want to have is something along the lines of:


$(':checkbox').each(function(){
  var $(this).parent().attr('id') = [];
}

$(':checkbox').click(function(){
  $(this).parent().attr('id').push($(this).val());
});

I know in PHP you can use the following to a similar effect:


foreach($array as $key => $value){
  $$key = $value;
}

Is that possible in javascript or am I being a little optimistic?

Thanks in advance,
Mike

Hi Mike,

You can assign a variable on an object using the array syntax when you have strings as keys. These are identical for example,


var varName = 'name';
obj.name == obj['name'] == obj[varName];

so all you need is an object(can be window) if you want it in the global scope. Or something else.


var data = {};
...
var varName = $(this).parent().attr('id');
data[varName] = [];
window[varName] = [];

This is my second favorite feature of javascript, nearly everything behaves like a hash.

Brilliant, thanks!