格式化树数据:
function replaceNameWithTitle(data) {
// 遍历数据数组
return data.map(item => {
// 复制当前对象,以免修改原始数据
const newItem = { ...item };
// 将 name 属性替换为 title
newItem.title = newItem.name;
newItem.key = newItem.uuid;
newItem.value = newItem.uuid;
// 删除原始的 name 属性
// delete newItem.name;
// newItem.disabled = newItem?.level != 1
// 如果当前对象有 children 属性,递归处理子节点
if (newItem.children && newItem.children.length > 0) {
newItem.children = replaceNameWithTitle(newItem.children);
} else {
newItem.children = null
}
// 返回处理后的对象
return newItem;
});
}
const treeData = useMemo(() => replaceNameWithTitle(modelTreeData?.children || []), [modelTreeData])
所有数据数组:
const getParentKey = (key, tree) => {
let parentKey;
for (let i = 0; i < tree.length; i++) {
const node = tree[i];
if (node.children) {
if (node.children.some((item) => item.key === key)) {
parentKey = node.key;
} else if (getParentKey(key, node.children)) {
parentKey = getParentKey(key, node.children);
}
}
}
return parentKey;
};
const dataList = useMemo(() => {
let newdataList = []
const generateList = (data) => {
for (let i = 0; i < data.length; i++) {
const node = data[i];
const { id, title, level } = node;
newdataList.push({ key: id, title: title, level: level });
if (node.children) {
generateList(node.children);
}
}
};
generateList(deviceTypeListData)
return newdataList
}, [treeData])
标签:node,格式化,data,Tree,key,newItem,const,数据,children From: https://www.cnblogs.com/Simoon/p/18191683