2 回答
TA贡献2037条经验 获得超6个赞
你的输出格式应该有问题,起码
label: 'AAA', department:'AAA-D1', office: 'AAA-D1-O1', pass: 6, onhold: 15, // company level 是不合理的,最多是label: 'AAA', pass: 6, onhold: 15, // company level 吧
如果数据能够保证全是这样的结构(只有如上的3级),其实还是比较好处理的。
var moriginalData= [
{ company: 'AAA', department:'AAA-D1', office: 'AAA-D1-O1', pass: 1, onhold: 3},
{ company: 'AAA', department:'AAA-D1', office: 'AAA-D1-O2', pass: 3, onhold: 5},
{ company: 'AAA', department:'AAA-D2', office: 'AAA-D2-O1', pass: 2, onhold: 7},
{ company: 'BBB', department:'BBB-D1', office: 'BBB-D1-O1', pass: 1, onhold: 3},
{ company: 'BBB', department:'BBB-D2', office: 'BBB-D2-O1', pass: 4, onhold: 3},
{ company: 'BBB', department:'BBB-D3', office: 'BBB-D3-O1', pass: 1, onhold: 3}
];
function a2o(originalData){
var outData=[];
var outObj={};
for(var i=0;i<originalData.length;i++){
var company= originalData[i].company;
var department= originalData[i].department;
var office={label:originalData[i].office, pass:originalData[i].pass, onhold:originalData[i].onhold};
if(outObj[company]===undefined){
outObj[company]={childrenKey:[], pass:0, onhold:0};
}
if(outObj[company][department]===undefined){
outObj[company][department]={children:[], pass:0, onhold:0 };
outObj[company].childrenKey.push(department)
}
outObj[company][department].children.push(office);
outObj[company][department].pass=outObj[company][department].pass+office.pass;
outObj[company].pass=outObj[company].pass+office.pass;
outObj[company][department].onhold=outObj[company][department].onhold+office.onhold;
outObj[company].onhold=outObj[company].onhold+office.onhold;
}
for( var com in outObj){
var tmpA={label:com, pass:outObj[com].pass, onhold:outObj[com].onhold, children:[]};
for (var j=0; j<outObj[com].childrenKey.length; j++ ){
var tD=outObj[com][ outObj[com].childrenKey[j] ];
tmpA.children.push({label:outObj[com].childrenKey[j] ,
pass:tD.pass ,
onhold:tD.onhold ,
children:tD.children} );
}
outData.push(tmpA);
}
return outData;
}
var treeDate=a2o(moriginalData)
console.log(treeDate);
添加回答
举报