开发者

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开发者_如何学C 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


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; 


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜