我有以下格式的平面文件数据:
d1 | d2 | d3 | d4
-------------------------------------------
Heading | | |
| Subheading | |
| | Entry1 |
| | Entry2 |
| Another sub | |
| | Entry3 |
| | Entry4 |
| | | Subentry
我可以很好地阅读平板电视,并希望将其分层,如果可能的话。我想知道我是否可以在.parentId()内访问前面的行并检查它是否是父。
或者我是否编写自己的树函数?
答案 0 :(得分:2)
所以我通过编写自己的树来实现它,就像这样:
function tree(nodes) {
var curr, parent, root;
var lev = 1;
nodes.forEach(function(d) {
if (!root) {
// handle root (first node)
curr = {
name: d.d1,
size: 1, //stub
children: []
};
root = curr;
parent = curr;
} else {
if (d['d' + (lev+1)]) {
// handle children
lev = lev+1;
parent = curr;
} else if (d['d' + (lev-1)]) {
// handle moving up the hierarchy
lev = lev-1;
parent = parent.parent;
} else if (!d['d' + lev]) {
// if it's neither child, nor moving up, nor a sibling, handle exception
throw "unhandled tree level";
}
curr = {
name: d['d' + lev],
size: 1, //stub
children: []
};
curr.parent = parent;
parent.children.push(curr);
}
});
return root;
}