树结构
1、实现类似于复选框的联动,同步父节点以及子节点某个属性状态
updateState(row, type) {
// 同步父节点对应type字段状态
const updateParentState = node => {
const parentRow = this.$refs.xTable.getParentRow(node) // 根据树结构递归或者其他方法获取
if (!parentRow) return
const isSameState = parentRow.children.every(item => item[type] === row[type])
// 同步父节点状态
if (isSameState) {
parentRow[type] = row[type]
} else {
parentRow[type] = false
}
updateParentState(parentRow)
}
// 同步子节点对应type字段状态
const updateChildrenState = node => {
const childrenRow = node?.children || []
if (!childrenRow.length) return
childrenRow.forEach(item => {
item[type] = row[type]
updateChildrenState(item)
})
}
updateParentState(row)
updateChildrenState(row)
}
2、扁平化数组相互转换
TreeToArr
(1)原生js
function fn(obj, res = []) { // 默认初始结果数组为[]
res.push(obj); // 当前元素入栈
// 若元素包含children,则遍历children并递归调用使每一个子元素入栈
if (obj.children && obj.children.length) {
for(const item of obj.children) {
fn(item, res);
}
}
return res;
}
fn(arr);
(2)利用loadsh
import _ from 'lodash'
const flattenTree = (tree, parentId = null) => {
return _.flatMap(tree, node => {
let { Code: id, Children: children, Name: text, Guid, ...rest } = node
return [{ ...rest, id, text, parentId, Guid }, ...flattenTree(children, id)]
})
}
return flattenTree(dataClone)
ArrToTree
/**
* @param {arr: array 原数组数组, id: number 父节点id}
* @return {children: array 子数组}
*/
function getChildren(arr, id) {
const res = [];
for (const item of arr) {
if (item.pid === id) { // 找到当前id的子元素
// 插入子元素,每个子元素的children通过回调生成
res.push({...item, children: getChildren(arr, item.id)});
}
}
return res;
}
getChildren(arr, 0);
评论
匿名评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果