如何减少深层嵌套数组并获得某些键的最大价值? 这是我的数据格式:
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(数组)从中获得最大的价值。
答案 0 :(得分: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
并遍历它并将值保存到最终数组中!
答案 1 :(得分: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
我可能在某个地方犯了一个错误,但你可以用这个一般的想法来产生预期的结果。
答案 2 :(得分:1)