构造树
/**
* 构建树结构
*
* @return {Array} 树结构[{id:树id,children:[]}]
*/
buildTree() {
const CHINA_ID = 998;
const FOREIGN_ID = 999;
return [this.buildNode(CHINA_ID), this.buildNode(FOREIGN_ID)];
},
buildNode(id) {
return {id: id, children: this.buildChildren(id)};
},
buildChildren(childId) {
let childrenArray = [];
const FILIATION = regionTools.filiation;
let array = FILIATION[childId];
if (array) {
for (let child of array) {
childrenArray.push(this.buildNode(child));
}
}
return childrenArray;
}
获取树所有节点
let tree = {
id: 1,
children: [
{ id: 2, children: [
{ id: 3 },
{ id: 4 }
] },
{ id: 5, children: [{id:9, children:[]}] },
{ id: 6, children: [] },
{ id: 7, children: [] },
{ id: 8, children: [] }
]
};
let expand = (tree = {}) => {
let { id, children } = tree;
let output = [];
output.push(id);
if (children && children.length) {
for (let c of children) {
output = output.concat(expand(c));
}
}
return output;
};
console.log(expand(tree));