2016-03-29 30 views
0

私は次のJSON構造を持っています。私はd3視覚化のすべてを表示するのではなく、各カテゴリ(area_description)のランダムな要素を取りたいと思います。私はそれを達成する最もクリーンな方法は何ですか?私の考えは、JSONをエリア記述でソートし、各カテゴリの開始と終了を取得して要素を取得することでした。JSONからn個の要素を取り除く方法

[ 

{ 

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

}] 
+0

は、最初に検索してみてください。http://stackoverflow.com/a/19270021/5004923 – webdeb

答えて

0

私はこれを試してみてください、多分それはとてもきれいではない、機能を書いた:

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; 
} 
関連する問題