这样树结构的数组:
let tree =[ {id: '1', title: '节点1', children: [ { id: '1-1', title: '节点1-1', children: [ { id: '1-1-1', title: '节点1-1-1' },] }, { id: '1-2', title: '节点1-2' } ] }, { id: '2', title: '节点2', children: [ { id: '2-1', title: '节点2-1' } ] } ]
我想把其中的某项取出创建新的数组,结构不变,例如这样
getTree =[ { title: '节点1', children: [ { title: '节点1-1', children: [ { title: '节点1-1-1' },] }, { title: '节点1-2' } ] }, { title: '节点2', children: [ { title: '节点2-1' } ] } ]
不知道怎么写,不知道描述清楚没,我是新手,不耻下问啊...
已解决
悬赏分:40
- 解决时间 2021-11-27 23:21
点赞 0反对 0举报 0
收藏 0
分享 0
回答2
最佳
-
你可以先了解一下什么是 递归
这个需求通过递归可以很轻易实现function getTree(ary) { return ary.map(v => { const item = { title: v.title, //这是创建的新对象 根据需要的键随意更改 }; if (v.children) item.children = getTree(v.children); return item; }); }
const newTree = getTree(tree); console.log(newTree)
支持 0 反对 0 举报2021-11-27 07:48