如何基于变量循环JSON数组?

时间:2015-08-18 15:37:28

标签: javascript json

我已经遍历了我的第一个JSON字符串,它给了我一个在div中显示的变量值(“lstr”)。基于这第一个值,我想循环遍历我的第二个JSON字符串以填充下拉框。变量值“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:

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",

        }
    }
}

根据“lstr”值为蓝色,绿色或黄色,它将在下拉框中填充1,2,3个对象及其相关的url值。我希望这是有道理的?任何帮助都会很好吗?!

1 个答案:

答案 0 :(得分:0)

就像评论所说的那样,你需要将你的第二个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",
          }
        }
    }
}

然后你可以使用

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