2014-01-16 84 views
0

我將如何減少一堆深度嵌套數組並獲得某些鍵的最大值? 這裏是我的數據格式:javascript d3從多嵌套數組/對象數據集中獲取最大值

var data = [ 
{ 
"category": "Cat 1", 
"subcategories": [ 
    { 
    "subcategory": "Subcate 1 a", 
    "problems": [ 
     { 
     "problem": "Problem 1 a 1", 
     "total": 3, 
     "breakdown": { 
      "moderate": 1, 
      "severe": 2 
     } 
     }, 
     { 
     "problem": "Problem 1 a 2", 
     "total": 6, 
     "breakdown": { 
      "moderate": 5, 
      "severe": 1 
     } 
     } 
    ] 
    } 
] 
}, 
{ 
"category": "Cat 2", 
"subcategories": [ 
    { 
    "subcategory": "Subcate 2 a", 
    "problems": [ 
     { 
     "problem": "Problem 2 a 1", 
     "total": 8, 
     "breakdown": { 
      "moderate": 5, 
      "severe": 3 
     } 
     } 
    ] 
    }, 
    { 
    "subcategory": "Subcat 2 b", 
    "problems": [ 
     { 
     "problem": "Problem 2 b 1", 
     "total": 4, 
     "breakdown": { 
      "moderate": 1, 
      "severe": 3 
     } 
     }, 
     { 
     "problem": "Problem 2 b 2", 
     "total": 2, 
     "breakdown": { 
      "moderate": 2, 
      "severe": 0 
     } 
     } 
    ] 
    } 
] 
} 
] 

如何我會得到「中等」和「嚴重」的每一個值的數組?所以在這個例子中,我需要

[1,2,5,1,5,3,1,3,2,0] 

然後,我想做d3.max(數組),以獲得它的最大價值。

回答

1

這是工作fiddle。只是將對象轉換成數組是這樣的:

var array = $.map(data, function(value, index) { 
      return [value]; 
    }); 

var arr =[]; 

for(var key in array) 
{ 
    var subcategories = array[key]['subcategories']; 
    for(var j in subcategories) 
    {  
     var prob = subcategories[j]['problems']; 
     for(var i in prob) 
     { 
      var moderate = prob[i]['breakdown']['moderate']; 
      var severe = prob[i]['breakdown']['severe']; 
      arr.push(moderate); 
      arr.push(severe); 
     } 
    } 
} 
alert(arr); //required array 
var max = d3.max(arr) //required max value 

,並遍歷它和值保存到最終的陣!

+0

那肯定做的工作,感謝你們爲您輸入。 – rowyourboat

+0

雖然這確實工作正常,但我最初發布的問題是因爲我想知道是否有避免在for循環中執行循環的方法。我一直在玩複雜的減少功能,並不能相當破解它。 – rowyourboat

1

這是有點囉嗦,但它可能工作:

var array = new Array(); 
for (var h=0; h<data.length; h++){ 
    for (var i=0; i<data[h].length; i++){ 
     for (var j=0; j<data[h].subcategories[i].length; j++){ 
      for (var k=0; k<data[h].subcategories[i].problems[j].length; k++){ 
       array.push(data[h].subcategories[i].problems[j].breakdown.moderate); 
       array.push(data[h].subcategories[i].problems[j].breakdown.severe); 
      } 
     } 
    } 
} 
//Then get the max of array 

我可能犯了一個錯誤的地方,但你可以使用這個總體思路,以產生期望的結果。

1

爲了通過深度嵌套的JSON使用jsonpath jQuery插件

Fiddle

JS

var mod=jsonPath(data, '$..subcategories..problems..moderate'); 
var path=mod.concat(jsonPath(data, '$..subcategories..problems..severe')); 
$("#max").html(d3.max(path)); 
相關問題