\{ "name": "第一层",
index:1, "children":[
{ "name":"第二层",
index:2,
},{ "name":"第二层",
index:2, "children":[
{ "name":"第三层",
index:3,
},{ "name":"第三层",
index:3,
},
]
}
]
}想在这个树状图中添加他们每一层的index,
2 回答
慕村9548890
TA贡献1884条经验 获得超4个赞
最终写法。
function fun(arry){ for(let i in arry){ let menu = arry[i]; if(!menu['num']){ menu['num'] = 1; } if(menu['children'].length && menu['children']){ for(let j in menu['children']){ menu['children'][j]['num'] = arry[i]['num'] + 1; fun(menu['children']) } } } }
慕尼黑8549860
TA贡献1818条经验 获得超11个赞
var ary = { "name": "第一层", index:1, "children":[ { "name":"第二层", index:2, },{ "name":"第二层", index:2, "children":[ { "name":"第三层", index:3, },{ "name":"第三层", index:3, }, ] } ] }function level(obj) { if (!obj.level) { obj.level = 1 } if (!obj.children || !obj.children.length) { return } obj.children.forEach(function(el) { el.level = obj.level + 1 level(el) }) } level(ary)console.log(ary)
var ary = [{ "name": "第一层", index:1, "children":[ { "name":"第二层", index:2, },{ "name":"第二层", index:2, "children":[ { "name":"第三层", index:3, },{ "name":"第三层", index:3, }, ] } ] }, { "name": "第一层", index:1, "children":[ { "name":"第二层", index:2, },{ "name":"第二层", index:2, "children":[ { "name":"第三层", index:3, },{ "name":"第三层", index:3, }, ] } ] } ]function level(ary) { ary.forEach(function(el) { if (!el.level) { el.level = 1 } if (!el.children || !el.children.length) { return } el.children.forEach(function(item) { item.level = el.level + 1 }) level(el.children) }) } level(ary)console.log(ary)
一个对象,一个数组
添加回答
举报
0/150
提交
取消