[英]Flatten multiple nested hierarchial array - d3.js
I have an an array with four levels that I would like to have flattened. 我有一个有四个级别的阵列,我想要扁平化。
Simplified code with two starting array-elements and flattening of the lowest level: 带有两个起始数组元素的简化代码和最低级别的扁平化:
var tstArray = [{Count:2,Yr:2008,Dep:"NDep_1",Periodtype:"Week",Period:1,Beds:5},
{Count:9,Yr:2008,Dep:"NDep_2",Periodtype:"Week",Period:1,Beds:10}
];
console.log(tstArray);
tstArray = d3.nest()
.key(function(d) { return d.Periodtype;})
.key(function(d) { return d.Yr;})
.key(function(d) { return d.Period;})
.key(function(d) { return d.Dep;})
.rollup(function(d) {
return {"Count":d3.sum(d, function(g) {return g.Count; }), "Beds":d3.sum(d, function(j) {return j.Beds;})};
}).entries(tstArray);
console.log(tstArray);
tstArray = tstArray.map(function(d){
var Periodtype = d.key
var values1 = d.values.map(function(e){
var Yr = e.key
var values2 = e.values.map(function(f){
var Period = f.key;
var values3 = f.values.map(function(g){
return{'Dep':g.key,Count':+g.values.Count,'Beds':+g.values.Beds}
});
return {'Period':Period,'values3':values3}
});
var tmparr = [];
for ( var i = 0, len=values2.length; i < len; i++) {
for ( var j = 0, lenj=values2[i].values3.length; j < lenj; j++) {
tmparr.push({ 'Period':values2[i].Period,
'Dep':values2[i].values3[j].Dep,
'Count': +values2[i].values3[j].Count,
'Beds': +values2[i].values3[j].Beds
});
};
};
return{'Year':Yar,'values2':tmparr}
});
return{'Periodtype':Periodtype,'values1':values1} })
;
console.log(tstArray);
Now, I have one solution, I think. 现在,我想有一个解决方案。 I could just redo this for the lowest level (three more goes) but that seems to be a bad way to go about this.
我可以重做这个最低级别(另外三个),但这似乎是一个不好的方式来解决这个问题。 How can i get all the flattening in one go?
如何一次性完成所有的扁平化? I have tried but I have had little luck with values3.
我尝试过,但我对于值3没什么好运。 I still understand these concepts too shallowly.
我仍然太了解这些概念。 Help much appreciated.
非常感谢。
Ok, after some help on which routes to explore I settled for a for-loop, mainly because the arrays are fixed and it was the easiest to get my head around. 好的,在探索了哪些路线的帮助后,我决定使用for循环,主要是因为阵列是固定的,而且最容易理解。
var tmparr = [];
for ( var i = 0, len=values2.length; i < len; i++) {
for ( var j = 0, lenj=values2[i].values3.length; j < lenj; j++) {
tmparr.push({ 'Period':values2[i].Period,
'Dep':values2[i].values3[j].Dep,
'Count': +values2[i].values3[j].Count,
'Beds': +values2[i].values3[j].Beds
});
};
};
return{'Year':Yar,'values2':tmparr}
I then repeated this loop on the next level (I did this mainly for readability, by doing it this way I didn't have to nest more than two levels of for-loops). 然后我在下一个级别重复这个循环(我这样做主要是为了可读性,通过这样做我不需要嵌套两个以上级别的for循环)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.