如何从JSON中提取n个随机元素
How to take n random elements from JSON
我有以下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;
}
相关文章:
- Javascript - 如何按顺序从数组中挑选随机元素
- ReactJS-目标随机元素
- JQuery-随机元素在容器内的绝对位置和旋转
- 如何从JSON中提取n个随机元素
- 使用 javascript 回显数组的 4 个随机元素
- 如何从数组中获取随机元素而不重复并将其放入文本区域
- 使用 jquery 为每几个随机元素添加类
- 为变量分配有限集合中的随机元素
- 选择随机
- 元素
- 拼接删除JavaScript中的随机元素问题
- AngularJS:从JSON文件中获取三个随机元素
- Javascript 或 jQuery 在页面刷新时显示随机元素
- Jasmine中的spyOn函数,该函数从数组中返回随机元素
- 如何使用jquery随机元素排序
- 从javascript中的关联数组中获取随机元素
- 如何从数组中选择随机元素并将其从列表中删除
- 页面上的随机元素
- 从数组中获取随机元素返回相同的元素
- 选择随机元素
- 从redis集合中获得随机元素,没有重复