如何循环这个特定的json对象数组

时间:2016-09-02 11:04:44

标签: html arrays json

我创建了一个JSON对象,我想在div中显示:问题和选择数量格式。

如何循环,即在div中迭代这个特定的JSON对象数组?

[
    {
        "question": "php Developer ?",
        "type": "checkbox",
        "mandatory": "yes",
        "answer": [
            "a",
            "b",
            "c",
            "d"
        ],
        "answerss": [
            "a",
            "b",
            "c",
            "d"
        ]
    },
    {
        "question": "1+1",
        "type": "radio",
        "mandatory": "no",
        "answer": [
            "1",
            "2",
            "3",
            "4"
        ],
        "answerss": [
            "1",
            "2",
            "3",
            "4"
        ]
    }
]

Question
answer 1
answer 2
answer 3
answer 4

2 个答案:

答案 0 :(得分:0)

你需要使用javascript。你正在使用角度js? 如果不 .. 访问此链接可能会帮助您How do I dynamically populate html elements with JSON Data with Javascript not jQuery?

答案 1 :(得分:0)

Angular Js

您可以使用ng-repeat指令(如

)来实现此目的
<div ng-controller="MyCtrl">
  <div ng-repeat="question in questions">
      <div class="preview">Question - {{question.question}} </div>
         <div ng-repeat="answer in question.answerss">
           {{answer}}
         </div>
   </div>
</div>

工作jsfiddle - https://jsfiddle.net/z800015w/

Jquery

使用Jquery,您需要使用以下代码更新div的innerHTML -

$.each(questions, function(index, question){
    var newItem = "<div> Q - "+ question.question + "<div></br>Answer - </br>";
    $.each(question.answerss, function(index2, answer){
    newItem = newItem + answer+"</br>";
    });
    inHTML = inHTML + newItem+"</br>";  
});

请参阅演示 - https://jsfiddle.net/umd7nnhu/2/