0

I'm working on a page that has multiple lists:

<ul class="policies" id="p-1">
  <li><a href="p_1_1">Foo</a></li>
  <li><a href="p_1_2">Foo2</a></li>
</ul>
<ul class="policies" id="p-2">
  <li><a href="p_2_1">Foo</a></li>
  <li><a href="p_2_2">Foo2</a></li>
</ul>

Each one of these hrefs has an array with a matching name:

var p_1_1 = ['ab', 'az', 'tx', 'wz'];
var p_1_2 = ['av', 'bq', 'cf', 'ts'];

Whenever the user clicks on one of the list items, I'm using JavaScript/jQuery to append a dynamic number of images to an empty div. The sources of the images will be taken from the array items:

$('li a').on('click', function(e) {
  e.preventDefault();
  var useArray = $(this).attr('href').toString();
} );

for ( var i=0; i < array.length; i++ ) {
  $('div').append('<img src="'+ array[i] +'" />');
}

My question is, how can I match the href attribute to the proper array name in order to output the right set of items? For example, when a user clicks on <a href="p_1_1">, I need to output the items from array p_1_1. My experience with arrays in JavaScript is very limited, and appreciate any help on the subject.

kylesimmonds
  • 183
  • 2
  • 11
  • 1
    `window[useArray]` if it's in the global scope, but you'd be better of with an object and using keys – adeneo Mar 17 '14 at 20:01

1 Answers1

2

Instead of separate arrays, wrap them all up in an object using your strings as keys:

var myStuff = {
    p_1_1 : ['ab', 'az', 'tx', 'wz'],
    p_1_2 : ['av', 'bq', 'cf', 'ts']
};

Now you can retrieve them easily with:

var foo = myStuff["p_1_1"];

Or in your code:

var useArray = $(this).attr('href').toString();
var array = myStuff[useArray];
Matt Burland
  • 44,552
  • 18
  • 99
  • 171
  • Thank you very much! I had tried using `window[useArray]`, which only returned `undefined`, but didn't have the proper understanding of objects and keys. – kylesimmonds Mar 17 '14 at 20:27