// 给树形json 分配所在层level及索引index pId暂时没用上第三个参数可以不用传 data是json数据 export function treeJsonLevel(data: any) { const dataCopy = JSON.parse(JSON.stringify(data)); const result = 1; const filter = (data: any, result: number, parent: any) => { if (Array.isArray(data)) { // 判断是否是数组并且没有的情况下, let index = 0; data.forEach(item => { item.level = result; item.dataLength = data.length; item.pId = parent?.key; item.index = index; index++; if (item.children) { result++; filter(item.children, result, item); // 递归调用下边的子项 result--; } }); } }; filter(dataCopy, result, null); // 调用一下 return dataCopy; } // 排序 重置索引(因为上移下移之后索引会有变化) data是json数据 export function treeJsoIndex(data: any) { const dataCopy = JSON.parse(JSON.stringify(data)); const filter = (data: any) => { if (Array.isArray(data)) { // 判断是否是数组并且没有的情况下, let index = 0; data.forEach(item => { delete item.index; item.index = index; index++; if (item.children) { filter(item.children); // 递归调用下边的子项 } }); } }; filter(dataCopy); // 调用一下 return dataCopy; } // 菜单升序 data是json数据 filterData要移动的数据 export function treeMenuUp(data: any, filterData: any) { let hasFound = false; // 表示是否有找到id值 const dataSource = data; const filter = (data: any) => { if (Array.isArray(data) && !hasFound) { // 判断是否是数组并且没有的情况下, data.map((item: any, index: number) => { if (item.key === filterData.key) { data[index] = data.splice(index - 1, 1, data[index])[0]; hasFound = true; // 并且找到id值 } else { filter(item.children); // 递归调用下边的子项 } }); } }; filter(dataSource); // 调用一下 data = treeJsoIndex(data); return data; } // 菜单降序根据索引插入指定位置 data.splice(count + 1, 0, filterData); // data是json数据 filterData要移动的数据 export function treeMenuDown(dataOther: any, filterData: any) { let hasFound = false; // 表示是否有找到id值 const filter = (data: any) => { if (Array.isArray(data) && !hasFound) { // 判断是否是数组并且没有的情况下, data.map((item: any, index: number) => { if (item.key === filterData.key) { const count = cloneDeep(filterData.index); data.splice(index, 1); data.splice(count + 1, 0, filterData); hasFound = true; // 并且找到id值 } else { filter(item.children); // 递归调用下边的子项 } }); } }; filter(dataOther); dataOther = treeJsoIndex(dataOther); return dataOther; }
tree json table 数据上移及下移功能
于 2022-07-05 17:59:50 首次发布