jQuery - $.each 循环遍历变量对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1909640/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:23:21  来源:igfitidea点击:

jQuery - $.each loop through variable object

jqueryjsonobjectloops

提问by SDG

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

我正在使用具有多个高级对象的 JSON 数据集。如果我从字面上声明对象名称,我可以毫无问题地循环遍历 JSON,但是当我在它的位置使用变量时,我会得到错误。它似乎试图将变量名称应用为对象的文字名称。这是一个快速示例

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.

在这种情况下,如何让它使用 activeList 的值?需要明确的是,变量 activeList 正确返回所选选项的值。如果 activeList 的值为“Christmas_List”,则循环遍历 data.activeList 应该循环遍历 JSON 数据中的 Christmas_List 对象。这不起作用,看来 data.activeList 正在寻找“activeList”对象。如果我在 activeList 的位置 (Christmas_List) 尝试文字值,则循环正常工作。

Any ideas? Thanks

有任何想法吗?谢谢

回答by John Foster

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; 

回答by McPherrinM

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.

这将创建一个 :selected 值的列表。如果不是,请澄清问题。

回答by RHicke

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

$().val() 返回找到的第一个值,如果你想要它作为一个数组,你必须自己循环选择输入