封装公共方法:扁平数组转为树形数组
代码
src/utils/arr.js
/**
*
* @param {Array} flatArr 扁平数据
* @param {string} pid 上级数据的id,常用'pid'
* @returns
*/
// 扁平数组转为树形数组
export function arrToTree(flatArr, pid) {
const res = []
const map = flatArr.reduce((res, v) => (res[v.id] = v, v.children = [], res), {})
for (const item of flatArr) {
if (item[pid] === 0) {
res.push(item)
continue
}
if (item[pid] in map) {
const parent = map[item[pid]]
parent.children = parent.children || []
parent.children.push(item)
}
}
return res
}
main.js
import { arrToTree } from '@/utils/arr'
// 全局挂载
Vue.prototype.arrToTree = arrToTree
使用
this.nodeData = this.arrToTree(this.nodeArr, 'pid')
参考链接
本文来自博客园,作者:shayloyuki,转载请注明原文链接:https://www.cnblogs.com/shayloyuki/p/17000490.html
posted on 2022-12-23 13:31 shayloyuki 阅读(32) 评论(0) 收藏 举报
浙公网安备 33010602011771号