处理树形结构和级联选择器

it2023-03-13  79

解决方案

方法一
export function getTreeMenuRoutes(arr) { const menuData = [] arr.forEach(item => { if (item.pid === 0) { menuData.push(item) } }) menuData.forEach(item => { item.children = [] arr.forEach(item1 => { if (item.id === item1.pid) { item.children.push(item1) } }) }) return menuData }
方法二
// ========树状数据处理函数=============== export function setTreeData(arr) { // 删除所有的children, 以防止多次调用 if (JSON.stringify(arr) === '{}') { return } arr.forEach(function(item) { delete item.children }) const map = {} // 构建map arr.forEach(i => { map[i.id] = i // 构建以id为键 当前数据为值 }) const treeData = [] arr.forEach(child => { const mapItem = map[child.pid] // 判断当前数据的parentId是否存在map中 if (mapItem) { // 存在则表示当前数据不是最顶层的数据 // 注意: 这里的map中的数据是引用了arr的它的指向还是arr,当mapItem改变时arr也会改变,踩坑点 (mapItem.children || (mapItem.children = [])).push(child) // 这里判断mapItem中是否存在child } else { // 不存在则是顶层数据 treeData.push(child) } }) return treeData }
级联选择器

export function getCascaderData(arr) { var newArr = [] const map = new Map() arr.forEach(item => { if (map.has(item.category)) { map.get(item.category).children.push({ value: item.id, label: item.appname, id: item.id }) } else { map.set(item.category, { label: item.category, value: item.appname, id: item.id, children: [{ value: item.id, id: item.id, label: item.appname }] }) } }) newArr.push(...map.values()) return newArr }
最新回复(0)