用来记录总是忘 感兴趣的小伙伴可以持续优化呦~~~
第一个版本:自己写的第一个版本(最简单粗暴)
export function arrayToTreeRecursive(items=[], key = 'menuId', parentId = 0) {
const res = [] // 存放结果集
for (let i = 0; i < items.length; i += 1) {
if (items[i].parentId === parentId) {
items[i].children = arrayToTreeRecursive(items, key, items[i].id)
res.push(items[i])
}
}
return res
}
arrayToTreeRecursive(res.data, 'id')
第二个版本:在第一个版本进行了优化
export function arrayToTreeRecursive(items: Array<IFormData>, key = 'menuId', parentId = 0) {
const res = [] // 存放结果集
for (let i = 0; i < items.length; i += 1) {
if (items[i].parentId === parentId) {
// 当前父节点的子元素
const currentItem = items[i]
// 把子元素放到数组中
res.push(items[i])
// 删除当前元素,以后需要再进行遍历了
items.splice(i, 1)
// i下标要往前挪一次
i -= 1
// 在新的数组中进行子元素的编辑
res[res.length - 1].children = arrayToTreeRecursive(items, key, currentItem.id)
}
}
return res
}
第三个版本:在第二个版本进行了优化
export function arrayToTreeRecursive(items: Array<IFormData>, key = 'menuId', parentId = 0) {
const res = [] // 存放结果集
for (let i = 0; i < items.length; i += 1) {
if (items[i].parentId === parentId) {
// 当前父节点的子元素
const currentItem = items[i]
// 把子元素放到数组中
res.push(items[i])
// 删除当前元素,以后需要再进行遍历了
items.splice(i, 1)
// i下标要往前挪一次
i -= 1
/* 上一版本修改点 */
// 判断当前节点是否有子节点
if (JSON.stringify(items).indexOf(`"parentId":${currentItem[key]}`) !== -1) {
// 在新的数组中进行子元素的编辑
res[res.length - 1].children = arrayToTreeRecursive(items, key, currentItem[key])
}
/* 上一版本修改点 end*/
}
}
return res
}
网上的版本
export function arrayToTree(items: Array<IFormData>, key?: string) {
let k = 'menuId'
if (key) {
k = key
}
const res = [] // 存放结果集
const map: any = {}
// 判断对象是否有某个属性
const getHasOwnProperty = (obj: any, property: any) => {
return Object.prototype.hasOwnProperty.call(obj, property)
}
// 边做map存储,边找对应关系
// eslint-disable-next-line no-restricted-syntax
for (const i of items) {
if (i[k]) {
map[i[k]] = {
...i,
children: getHasOwnProperty(map, i[k]) ? map[i[k]].children : []
}
const newItem = map[i[k]]
if (i.parentId === 0) {
res.push(newItem)
} else {
if (!getHasOwnProperty(map, i.parentId)) {
map[i.parentId] = {
children: []
}
}
map[i.parentId].children.push(newItem)
}
}
}
return res
}