我试图在JS上构建一个迭代器,它将获取一个树,并在每次迭代时返回下一个可能的子树。
以下是源树的示例:
{
name: 'A',
children: [
{
name: 'B',
children: [
{
name: 'E'
},
{
name: 'F'
},
]
},
{
name: 'C',
}
]
}
结果应该是三次迭代
1. {
name: 'A',
children: [
{
name: 'B',
children: [
{
name: 'E'
}
]
}
]
}
2. {
name: 'A',
children: [
{
name: 'B',
children: [
{
name: 'F'
}
]
}
]
}
3. {
name: 'A',
children: [
{
name: 'C',
}
]
}
有人可以给我一个提示或指出如何解决这个问题的正确方向吗?
谢谢!
答案 0 :(得分:0)
这对你有帮助。
var arry=[];
var obj={
name: 'A',
children: [
{
name: 'B',
children: [
{
name: 'E'
},
{
name: 'F'
},
]
},
{
name: 'C',
}
]
};
for(i=0;i<obj.children.length;i++)
{
var newObj={name:obj.name,children:[{name:obj.children[i].name}]};
if(obj.children[i].children){
for(j=0;j<obj.children[i].children.length;j++)
{
var newObj={name:obj.name,children:[{name:obj.children[i].name,children: []}]};
newObj.children[i].children[0]= {name: obj.children[i].children[j].name};
arry.push(newObj);
}
}
else{
arry.push(newObj);
}
}
for(k=0;k<arry.length;k++){
console.log(arry[k]);
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
答案 1 :(得分:0)
我认为递归函数是你的答案。
这样的东西?
(它使用你的例子)
var newtrees = [];
var getTreeFromPath = function(path) {
var newtree = {};
var next = newtree;
for (var i = 0 ; i < path.length;i++) {
next.name = path[i].name;
if (path[i].children) {
var nextIteration = {};
next.children = [nextIteration];
}
next = nextIteration;
}
return newtree;
}
var iterateNode = function(node, pathToNode) {
if (!node.children) {
pathToNode.push(node);
newtrees.push(getTreeFromPath(pathToNode));
} else {
pathToNode.push(node);
for (var i = 0;i < node.children.length;i++) {
iterateNode(node.children[i], pathToNode);
}
}
};
iterateNode(tree, []);