简体   繁体   English

如何基于变量遍历JSON数组?

[英]How can I loop through a JSON array based on a variable?

I have already looped through my first JSON string and it gives me a variable value ("lstr") that is shown within a div. 我已经遍历了我的第一个JSON字符串,它为我提供了一个显示在div中的变量值(“ lstr”)。 Based on this first value I'd like to loop through my second JSON string to populate a dropdown box. 基于此第一个值,我想遍历第二个JSON字符串以填充一个下拉框。 The variable value "lstr" matches the "name" object in jsonString2: 变量值“ lstr”与jsonString2中的“ name”对象匹配:

//resultItems.push("After");
         var lstr = "";

         for (var j = 2; j < resultItems.length; j++) {
             lstr = lstr + resultItems[j] + "";

         }
         dom.byId("info").innerHTML = lstr;

     });

jsonString2: jsonString2:

var jsonString2 = 

{
    "Toplevel": {
        "name": "Blue",
        "service": {
            "1": "a url",
            "2": "a url",
            "3": "a url",
        },
        "name": "Green",
        "service": {
            "1": "a url",
            "2": "a url",
            "3": "a url",

        },
        "name": "Yellow",
        "service": {
            "1": "a url",
            "2": "a url",
            "3": "a url",

        }
    }
}

Depending on the the "lstr" value being blue, green or yellow it would then populate a dropdown box with the 1,2,3 objects and their related url values. 取决于“ lstr”值是蓝色,绿色还是黄色,然后将用1,2,3对象及其相关的url值填充下拉框。 I hope this makes sense? 我希望这是有道理的? Any help would be good?! 任何帮助都会好吗?

Like the comments have said, you need to re factor your second JSON object (jsonString2) to look like this: 就像评论中所说的那样,您需要重构第二个JSON对象(jsonString2)如下所示:

    var jsonString2 = 

{
    "Toplevel": {
      "Blue": {
         "service": {
            "1": "a url",
            "2": "a url",
            "3": "a url",
          }
        },
        "Green" : {
           "service": {
            "1": "a url",
            "2": "a url",
            "3": "a url",
           }
         },
        "Yellow" : {
          "service": {
            "1": "a url",
            "2": "a url",
            "3": "a url",
          }
        }
    }
}

Then you can use 那你可以用

for (var key in jsonStrng2[lstr].service){
 //add code to update dropdown here for each service
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM