js,遍历树形数组,大神 打扰了 最后次问你个问题哈 这次真得有点难
vara=[{"id":"1","text":"一","children":[{"id":"1-1","text":"test1","children":[{"id":"...
var a =[ {
"id" : "1",
"text" : "一",
"children" : [ {
"id" : "1-1",
"text" : "test1",
"children" : [ {
"id" : "1-1-1",
"text" : "test1-1",
}, {
"id" : "1-1-2",
"text" : "test1-2",
} ]
}, {
"id" : "1-2",
"text" : "test2",
"children" : [ {
"id" : "1-2-1",
"text" : "test2-1",
}, {
"id" : "1-2-2",
"text" : "test2-1",
} ]
} ]
}, {
"id" : "2",
"text" : "二",
"children" : [ {
"id" : "2-1",
"text" : "test1",
"children" : [ {
"id" : "2-1-1",
"text" : "test1-1",
} ]
} ]
} ];
上面树形数组
给个id想得到这个Id同层级或者父级的部分
例如:id="1-1"
得到:
[ {
"id" : "1",
"text" : "一",
"children" : [ {
"id" : "1-1",
"text" : "test1"
}, {
"id" : "1-2",
"text" : "test2"
} ]
}, {
"id" : "2",
"text" : "二",
"children" : [ {
"id" : "2-1",
"text" : "test1"
} ]
} ];
例如:id="1"
得到:
[ {
"id" : "1",
"text" : "一"
}, {
"id" : "2",
"text" : "二"
} ];
例如:id="1-1-1"
得到:保持不变没有子节点了
就是想得到同层和父层节点 展开
"id" : "1",
"text" : "一",
"children" : [ {
"id" : "1-1",
"text" : "test1",
"children" : [ {
"id" : "1-1-1",
"text" : "test1-1",
}, {
"id" : "1-1-2",
"text" : "test1-2",
} ]
}, {
"id" : "1-2",
"text" : "test2",
"children" : [ {
"id" : "1-2-1",
"text" : "test2-1",
}, {
"id" : "1-2-2",
"text" : "test2-1",
} ]
} ]
}, {
"id" : "2",
"text" : "二",
"children" : [ {
"id" : "2-1",
"text" : "test1",
"children" : [ {
"id" : "2-1-1",
"text" : "test1-1",
} ]
} ]
} ];
上面树形数组
给个id想得到这个Id同层级或者父级的部分
例如:id="1-1"
得到:
[ {
"id" : "1",
"text" : "一",
"children" : [ {
"id" : "1-1",
"text" : "test1"
}, {
"id" : "1-2",
"text" : "test2"
} ]
}, {
"id" : "2",
"text" : "二",
"children" : [ {
"id" : "2-1",
"text" : "test1"
} ]
} ];
例如:id="1"
得到:
[ {
"id" : "1",
"text" : "一"
}, {
"id" : "2",
"text" : "二"
} ];
例如:id="1-1-1"
得到:保持不变没有子节点了
就是想得到同层和父层节点 展开
1个回答
展开全部
这个可以理解写为有限深层的拷贝
var Deep,ID = '1-1',After = [];
~function(List,Level)
{
var T,F;
for (F = List.length;F;)
{
T = List[--F]
if (ID === T.id)
{
Deep = Level
return !0
}
if (T.children)
if (arguments.callee(T.children,Level + 1))
return !0
}
}(a,1)
//现在已经得到指定ID的深度了
~function(From,To,Deep)
{
var C,T,F,Fa;
--Deep
for (F = 0;F < From.length;++F)
{
T = From[F]
To.push(C = {})
for (Fa in T) /^children$/.test(Fa) || (C[Fa] = T[Fa])
if (Deep) arguments.callee(T.children,C.children = [],Deep)
}
}(a,After,Deep)
console.log(After)
追问
谢谢哈 刚刚测试了下 如果在"id" : "1-1",下面加个
"children" : [ {
"id" : "1-1-1-1",
"text" : "test1-1",
}]
然后指定ID='1-1-1-1' js报了个错
树形是无限层次
for (F = 0;F < From.length;++F)
Cannot read property 'length' of undefined
追答
~function(From,To,Deep)
{
var C,T,F,Fa;
if (!Deep) return
--Deep
for (F = 0;F < From.length;++F)
{
T = From[F]
To.push(C = {})
for (Fa in T) /^children$/.test(Fa) || (C[Fa] = T[Fa])
Deep && T.children && arguments.callee(T.children,C.children = [],Deep)
}
}(a,After,Deep)
来自:求助得到的回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询