SDG
SDG

Reputation: 183

jQuery - $.each loop through variable object

I'm working with a JSON dataset that has multiple high level objects. If I literally declare the object name, I can loop through the JSON with no trouble, but when I use a variable in its place, I get errors. It appears that it's trying to apply the variable name as the literal name of the object. Here's a quick example

function(data){
    var select = $('#lists select');
    var activeList = $(select+':selected').val();

    $.each(data.activeList, function(i,item){
      // Do stuff    
    });
}

How do I get it to use the value of activeList in this case? To be clear, the variable activeList correctly returns the value of the selected option. If the value of activeList is "Christmas_List", looping through data.activeList should loop through the Christmas_List object within the JSON data. This doesn't work, it appears that data.activeList is looking for the "activeList" object. If I try a literal value in activeList's place (Christmas_List), the loop works properly.

Any ideas? Thanks

Upvotes: 0

Views: 35812

Answers (3)

John Foster
John Foster

Reputation: 8755

Do you mean you have a situation something like this?

$(function() {
    var test = { Foo : [ 1, 2, 3], Bar : [4, 5, 6] }; // Your JSON object
    var prop = "Foo"; //Your select list value
    $.each(test[prop], function() { alert(this); });
});

In which case you want to access the object by key....

test[prop]

rather than directly

test.prop; 

Upvotes: 12

RHicke
RHicke

Reputation: 3614

$().val() returns the first value found if you want it as an array you will have to loop through the selected inputs yourself

Upvotes: 1

McPherrinM
McPherrinM

Reputation: 4614

I'm not entirely certain what you're trying to do here, however, your example code looks awkward, and so perhaps something like this is what you're looking for as an answer:

activeList = []
$(select+":selected").each( function(item) {
    activeList.append( $(item).val() )
});

This would create a list of the :selected values. If not, please clarify the question.

Upvotes: 3

Related Questions