🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
需求:使用树状数据渲染树,但后台提供的是数组数据 ~~~ const source = [ { id: 1, parentId: 0, name: "1" }, { id: 2, parentId: 0, name: "2" }, { id: 3, parentId: 0, name: "3" }, { id: 4, parentId: 1, name: "1-1" }, { id: 5, parentId: 1, name: "1-2" }, { id: 6, parentId: 2, name: "2-1" }, { id: 7, parentId: 3, name: "3-1" } ] const getTreeData = (source, mianId = 0) => { const cloneData = JSON.parse(JSON.stringify(source)) // 对源数据深度克隆 return cloneData.filter(father => { const branchArr = cloneData.filter(child => father.id === child.parentId)   // 返回每一项的子级数组 branchArr.length > 0 ? father.children = branchArr : '' // 如果存在子级,则给父级添加一个children属性,并赋值 return father.parentId === mianId // 返回第一层 }) } const arr = getTreeData(source) console.error("arr", arr) ~~~