moo moo
moo moo

Reputation: 484

Accessing dynamic variables in jQuery

I have an $.each in which I have category IDs like 103 or 104 that are set with cat_id.

Now, inside that function, i want to run another $.each to access an array which has items that are sorted by those category IDs, like:

$.each( data.menu_items.items_CATID, function( key, val ) {

                    $.each( val, function( key2, val2 ) {
                        htm3+=''+val2.item_name+'..';
                    });


});

So basically, I need to access data.menu_items.items_103 or data.menu_items.items_104.

How do I set the variable? I tried with:

data.menu_items.items_'+cat_id+'

and such but that doesn't work.

The data is basically an array like:

menu_items:
items_251: (9) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
items_252: (6) [{…}, {…}, {…}, {…}, {…}, {…}]

Upvotes: 0

Views: 43

Answers (2)

tcharlyson
tcharlyson

Reputation: 116

Not sure of what you need but, have you tried :

const itemId = `items_${catId}`
data.menu_items[itemId]

I hope this helps !

Upvotes: 1

Prawin soni
Prawin soni

Reputation: 452

Try this

data.menu_items['items_' + cat_id]

Upvotes: 2

Related Questions