如何从JSON中提取n个随机元素

How to take n random elements from JSON

本文关键字:随机 元素 提取 JSON      更新时间:2023-09-26

我有以下JSON结构,我想获取每个类别的n个随机元素(area_description),而不是在d3可视化中显示所有内容。我能做到这一点的最干净的方法是什么?我的想法是按照区域描述对JSON进行排序,得到每个类别的开始和结束,然后抓取元素。

[
{
    "id": ​1,
    "number": "2-1",
    "type": "GENERAL",
    "location": "US2",
    "floor": ​2,
    "area_description": "High Perfomance Computing",
    "status": "ASSIGNED"
},
{
    "id": ​2,
    "number": "2-2",
    "type": "GENERAL",
    "location": "US2",
    "floor": ​2,
    "area_description": "High Perfomance Computing",
    "status": "AVAILABLE"
},
{
    "id": ​3,
    "number": "2-3",
    "type": "GENERAL",
    "location": "US2",
    "floor": ​2,
    "area_description": "Cloud",
    "status": "AVAILABLE"
},
{
    "id": ​4,
    "number": "2-4",
    "type": "GENERAL",
    "location": "US2",
    "floor": ​2,
    "area_description": "Cloud",
    "status": "AVAILABLE"
},
{
    "id": ​5,
    "number": "2-5",
    "type": "GENERAL",
    "location": "US2",
    "floor": ​2,
    "area_description": "Static",
    "status": "ASSIGNED"
}]

我写了函数,也许它不太干净,试试这个:

function getRandom(json){
    var n = arguments[1] || 1;
    var assoc_array = [];
    var result      = [];
    var random_num  = 0;
    for(var i in json){
        if(json.hasOwnProperty(i)){
            if(typeof assoc_array[ json[i].area_description ] == 'undefined'){
                assoc_array[ json[i].area_description ] = [];   
            }
            assoc_array[ json[i].area_description ].push(json[i]);
        }
    }
    while(n > 0){
        for(var key in assoc_array){
            if(assoc_array.hasOwnProperty(key)){
                random_num = Math.floor(Math.random() * (assoc_array[ key ].length));
                if(typeof assoc_array[ key ][ random_num ] != 'undefined'){
                    result.push(assoc_array[ key ][ random_num ]);
                }
            }
        }
        n--;
    }
    return result;
}