简体   繁体   中英

How to take n random elements from JSON

I have the following JSON structure and I want to grab n random elements of each category (area_description) instead of displaying everything in a d3 visualization. What is the most clean way I can achieve that? My idea was to sort the JSON by area description and get the start and end of each category and then grab elements.

[

{

    "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"

}]

i wrote function, maybe it is not so clean, try this:

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;
}

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