从多维嵌套json数组创建下拉列表

时间:2015-04-08 10:46:49

标签: javascript jquery json

我需要创建drop 基于以下json数组的下行列表,将有5个下拉列表,如果我选择我需要填充其他四个,例如,如果我在第一个下拉列表中选择印地语然后

Second list           Third list         Forth list        Fifth list
     "History",        "Philosophy",   "Political Science"  "English"   
     "Sociology",       "BLANK"             "BLANK"           "BLANK"
     "Economics"                              

现在当我使用jquery来实现它时,列表没有正确填充。我无法分解内部数组。 我附加了jsfidle的链接。我是否需要更改json格式。

{
      "Hindi": [
        [
          "History",
          "Sociology",
          "Economics"
        ],
       "Philosophy",
        "Political Science",
        "English"
      ],
      "Bengali": [
        ["History" ,"Sociology"
        ],
        "Sanskrit",
        "Philosophy",
        "Political Science"
      ],
      "English": [["History","Sociology","Economics"],
        "Philosophy",
        "Political Science",
        ["Bengali","Hindi"]

      ]

    }

1 个答案:

答案 0 :(得分:0)

解析JSON时,假设每个下拉列表都具有相同的结构:

{"1select":[["2select values..."],[3select values..."],[4select values..."],[5select values..."]]} (如果没有array - >创建一个)

并且每次下拉都会这样做。

代码:

    var jsonObj = {"Hindi":[["History","Sociology","Economics"],"Philosophy","Political Science","English"],"Bengali":[["History","Sociology"],"Sanskrit","Philosophy","Political Science"],"English":[["History","Sociology","Economics"],"Philosophy","Political Science",["Bengali","Hindi"]]}

function updateSelect() {
    var getOpts = function(raw){
        var values = raw;
        if (!(raw instanceof Array)){
            values = [raw, ""];
        }
        var result = [];
        values.forEach(function(obj){
            result.push(new Option(obj, obj));
        });
        return result;
    };


    var newKey = $("#select1").val();
    var mappings = [{"#select2":0},{"#select3":1},{"#select4":2},{"#select5":3}];
    var selected = jsonObj[newKey];

    mappings.forEach(function(mapping){
        var selector = Object.keys(mapping)[0];
        var index = mapping[selector];
        $(selector).empty();
        var opts = getOpts(selected[index]);
        $(selector).append(opts);
    });

}

$(document).ready(function() { 
    $("#select1").change(updateSelect);
    updateSelect(); // For initial page load.
});

示例:here