简体   繁体   中英

How can I shuffle or randomize JSON object array data?

I am working on a quiz app. I have been trying to figure out how I can shuffle the options in a quiz question.

I have researched all over, the closest I found was this: shuffle array in ng-repeat angular

However, I was unsuccessful in implementing the shuffleArray() function. It wouldn't work for me.

I have created a jsfiddle http://jsfiddle.net/fa4v8/121/

This is my ng-repeat:

<div ng-controller="MyCtrl">
    <p ng-repeat="(key,i) in options">{{options[key].text}}</p>
</div>

and this is my controller:

var myApp = angular.module('myApp', []);

function MyCtrl($scope) {
    $scope.options = {
            "d": {
            "text": "Answer1-d"
        },
            "c": {
            "text": "Answer1-c"
        },
            "a": {
            "text": "Answer1-a"
        },
            "b": {
            "text": "Answer1-b"
        }
    }
}

the output keeps coming in this order: (a,b,c,d)

Answer-a

Answer-b

Answer-c

Answer-d

Is there a way to make the options displayed in the order as the $scope.options (d,c,a,b) or display them in random order?

Working example that would help you: http://jsfiddle.net/owenmead/fa4v8/1/ taken from https://stackoverflow.com/a/21587316/3335993 , just sort them in your controller and assign a random rank in each iteration.

function MyCtrl($scope) {
    $scope.list = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
    $scope.random = function() {
        return 0.5 - Math.random();
    }
}

Actually the ng-repeat will return the keys of the object exectly in the order as they have been defined - as long as you use Angular version 1.4 and above. Up to version 1.3 the ngRepeat directive used to sort the keys alphabetically. The jsfiddle you provided is using version 1.0...

See this plunk http://plnkr.co/edit/bStyZU And this explanation https://docs.angularjs.org/api/ng/directive/ngRepeat

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM