1

So I have an array something like this:

var first_array = ['foo','bar','foobar'];

I am running a click function and trying to get the name of the array and loop through the array which has first as the ID name something like this

$('element').on('click',function(){
    var id = $(this).attr('id');
    var arr = id+"_array";
    $.each(arr,function(index,value){
        console.log(value);
    })
})

Now the arr gives a variable name first_array and not the array. Hence the each loop fails. Is there a way to reference the array? I need to dynamically create the array variable name and get the array elements. I have also tried declaring the array globally and inside the click function but does not work.

4
  • 2
    first_array will be a string... You should use t as a key of the object... Commented Apr 26, 2016 at 7:47
  • And initial object should be: var obj = {first_array:['foo','bar','foobar']}; Commented Apr 26, 2016 at 7:47
  • @RayonDabre And what if I have multiple arrays. Can I include all in obj like var obj = {first_array:['foo','bar','foobar'],second_array:['bar','foo']}. Will try it out. Commented Apr 26, 2016 at 7:54
  • You best keep you arrays in an object and access through bracket notation like myArrays[first_array] or if it is in global scope than access it like window[first_array] where first_array is a dynamic variable holding the array name. Commented Apr 26, 2016 at 8:40

2 Answers 2

1

Like Rayon Dabre said in the comments, you should use a parent object containing your first_array, and more, like that :

var parent_array = {
    first_array: ['foo','bar','foobar'],
    second_array: ['foo2', 'bar2', 'foobar2']
};

$('element').on('click',function(){
    var id = $(this).attr('id');
    var arr = parent_array[id+"_array"];
    $.each(arr,function(index,value){
        console.log(value);
    })
});
Sign up to request clarification or add additional context in comments.

1 Comment

parent array ? Do you mean Object ?
0

You can put all your arrays into a javascript object or a parent array and access them by key/name like parentArr["first_array"]

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.