15

我有一个 json 对象作为

[
{"DisplayName":"Answer Number 1","Value":"Answer1","Option":"True"},
{"DisplayName":"Answer Number 1","Value":"Answer1","Option":"False"},
{"DisplayName":"Answer Number 2","Value":"Answer2","Option":"True"},
{"DisplayName":"Answer Number 2","Value":"Answer2","Option":"False"}
]

我需要的是从这个对象创建 2 个下拉菜单作为

答案 1 -> 真/假

答案 2 -> 真/假

下拉部分我会做我自己..我只是对如何迭代这个对象感到困惑。任何人都可以带我举一些例子吗?

4

4 回答 4

31

您的 json 对象jsonObject存储在一个数组中。做 :

$.each(jsonArray, function(index,jsonObject){
    $.each(jsonObject, function(key,val){
        console.log("key : "+key+" ; value : "+val);
    });
});

它会给你

key : DisplayName ; value : Answer Number 1
key : Value ; value : Answer 1
key : Option ; value : true

无论如何,安东尼是对的。您的结构将难以操作

于 2013-06-19T08:34:46.083 回答
4

您的 JSON 无效。那这个呢 :

var json = '[
    {"DisplayName":"Answer Number 1","Value":"Answer1","Option":"True"},
    {"DisplayName":"Answer Number 1","Value":"Answer1","Option":"False"},
    {"DisplayName":"Answer Number 2","Value":"Answer2","Option":"True"},
    {"DisplayName":"Answer Number 2","Value":"Answer2","Option":"False"}
]';
var jsonObject = $.parseJSON(json); //Only if not already an object
$.each(jsonObject, function (i, obj) {
    alert(obj.DisplayName);
});

小提琴

于 2013-06-19T08:44:34.423 回答
1

使用jQuery.each()

$.each( yourArrayOfObjects, function( index, object ){
  // do your magic here
});
于 2013-06-19T08:32:55.917 回答
0
var json = [{
    "DisplayName": "Answer Number 1",
        "Value": "Answer1",
        "Option": "True"
}, {
    "DisplayName": "Answer Number 1",
        "Value": "Answer1",
        "Option": "False"
}, {
    "DisplayName": "Answer Number 2",
        "Value": "Answer2",
        "Option": "True"
}, {
    "DisplayName": "Answer Number 2",
        "Value": "Answer2",
        "Option": "False"
}];

迭代

    for (i in json) {
//json[i] is your current object inside the array, {"DisplayName":"Answer Number 1","Value":"Answer1","Option":"True"}
        for (key in json[i]) {
// keys are DisplayName,  Value, Option
            alert(key);
            alert(json[i][key]); // instead of writing object.key you can also write object[key]
        }
    }
于 2013-06-19T08:34:03.030 回答