100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > (js)扁平数组树状化 树状数组扁平化

(js)扁平数组树状化 树状数组扁平化

时间:2024-02-03 04:29:57

相关推荐

(js)扁平数组树状化 树状数组扁平化

扁平数组树状化(利用递归,两个函数完成树状转化)

数组格式:

let list = [{ id: 1, title: '标题1', p_id: 0 },{ id: 2, title: '标题2', p_id: 0 },{ id: 3, title: '标题2-1', p_id: 2 },{ id: 4, title: '标题2-2', p_id: 2 },{ id: 5, title: '标题2-2-1', p_id: 4 },{ id: 6, title: '标题2-2-1-1', p_id: 5 },{ id: 7, title: '标题2-2-1-2', p_id: 5 },]

function getTree (arr) {const treeData = []arr.forEach(v => {//找到第一层父节点if (v.p_id === 0) {treeData.push(v)v.children = getChildren(arr, v.id)}})return treeData}

function getChildren (arr, id) {const children = []//查找父节点对应的子节点arr.forEach(v => {if (v.p_id === id) {v.children = getChildren(arr, v.id)children.push(v)}})return children}console.log(getTree(list))//打印输出结果

树状数组扁平化

直接利用上面转化结果进行扁平化

//树状扁平化function flatten (data) {return data.reduce((pre, cur) => {const { id, title, p_id, children = [] } = curreturn pre.concat([{ id, title, p_id }], flatten(children))}, [])}console.log(flatten(fu(list)))

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。