按优先级排序json对象然后随机化所有els

时间:2016-11-04 09:13:04

标签: jquery json object random

也许有人可以提供帮助。我不能自己解决这个问题:( 我有json对象列表:

{"widget_foto": {"photos": [
    {
        "picThumb": "../../preview_stuff/img/widget-3-1.png",
        "picOrig": "../../preview_stuff/img/widget-3-1.png",
        "galeryUrl": "",
        "shareUrl": "",
        "priority": 0
    },
    {
        "picThumb": "../../preview_stuff/img/widget-3-2.png",
        "picOrig": "../../preview_stuff/img/widget-3-2.png",
        "galeryUrl": "",
        "shareUrl": "",
        "priority": 2
    },}}

我需要按优先顺序排序对象,我已经完成了,但是我无法弄清楚如何随机化优先级为0的对象或者对象优先级是否相等。

到目前为止,这是我的代码。

$(function(){
var url="../json/foto.json";
$.getJSON(url, function(json){
    var fotoWidget = json.widget_foto;
    var widget3 = ".col-widget-3" + " ";

    //Populate content
    var byPriority = fotoWidget.photos.slice(0);

    byPriority.sort(function(a,b){
        return b.priority - a.priority;
    });
    $.each(byPriority, function(index, value){
        $(widget3 + ".widget-3-" + (index + 1)).css({"background-image": "url(images/" + value.picOrig + ")"});
    });
});

任何帮助都会受到影响。

1 个答案:

答案 0 :(得分:1)

您可以先随机洗牌,然后按优先级排序。

var data = [
    {id:"0", "p":0},
    {id:"1", "p":0},
    {id:"2", "p":5},
    {id:"3", "p":5},
    {id:"4", "p":2},
    {id:"5", "p":2},
    {id:"6", "p":4},
    {id:"7", "p":4},
    {id:"8", "p":1},
    {id:"9", "p":1}
]
function shuffleArray(array) {
    for (var i = array.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
    return array;
}
shuffleArray(data)
data.sort( (a, b) => a.p - b.p )
JSON.stringify(data)