如何在Angularjs中随机化JSON

时间:2016-04-13 06:32:36

标签: angularjs

如何在angularjs中随机化我的以下JSON ???

{
  "1": {
            "id": "1",
            "que": "Grand Central Terminal, Park Avenue, New York is the world's",
            "options": {
                "A": "largest railway station",
                "B": "highest railway station",
                "C": "longest railway station",
                "D": "None of the above"
            },
            "ans": "A"
        },
 "2": {
            "id": "2",
            "que": "Entomology is the science that studies",
            "options": {
                "A": "Behavior of human beings",
                "B": "Insects",
                "C": "The origin and history of technical and scientific terms",
                "D": "The formation of rocks"
            },
            "ans": "B"
        },
 "3": {
            "id": "3",
            "que": "Eritrea, which became the 182nd member of the UN in 1993, is in the continent of",
            "options": {
                "A": "Asia",
                "B": "Africa",
                "C": "Europe",
                "D": "Australia"
            },
            "ans": "B"
        }
}

2 个答案:

答案 0 :(得分:0)

一种解决方案是将您的问题对象转换为数组,以便随机化问题顺序:

http://plnkr.co/edit/PSeh0BLNjK5ydXJrLguw?p=preview

<p ng-repeat="q in questionsArray | orderBy: random">{{q.key}} - {{q.val.que}}</p>

答案 1 :(得分:0)

为了让你的工作更轻松,我建议你使用像这样的对象数组:

var questions=
[
    {
        "id": "1",
        "que": "Grand Central Terminal, Park Avenue, New York is the world's",
        "options": {
            "A": "largest railway station",
            "B": "highest railway station",
            "C": "longest railway station",
            "D": "None of the above"
        },
        "ans": "A"
    },
    {
        "id": "2",
        "que": "Entomology is the science that studies",
        "options": {
            "A": "Behavior of human beings",
            "B": "Insects",
            "C": "The origin and history of technical and scientific terms",
            "D": "The formation of rocks"
        },
        "ans": "B"
    },
    {
        "id": "3",
        "que": "Eritrea, which became the 182nd member of the UN in 1993, is in the continent of",
        "options": {
            "A": "Asia",
            "B": "Africa",
            "C": "Europe",
            "D": "Australia"
        },
        "ans": "B"
    }
]

然后选择随机问题:

$scope.randomQuestion = questions[Math.floor(Math.random()*questions.length)];