記錄一下日常學(xué)習(xí)雾叭,js數(shù)組扁平數(shù)據(jù)結(jié)構(gòu)轉(zhuǎn)tree
演示數(shù)據(jù)
const arr = [
{ id: 1, name: '部門1', pid: 0 },
{ id: 2, name: '部門2', pid: 1 },
{ id: 3, name: '部門3', pid: 1 },
{ id: 4, name: '部門4', pid: 3 },
{ id: 5, name: '部門5', pid: 4 },
]
1.map存儲 唯一性
function formatDataTree (arr, key, parentKey) {
const result = [];
const itemMap = {};
for (const item of arr) {
const id = item[key];
const pid = item[parentKey];
if (!itemMap[id]) {
itemMap[id] = {
children: [],
}
}
itemMap[id] = {
...item,
children: itemMap[id]['children']
}
const treeItem = itemMap[id];
if (pid === 0) {
result.push(treeItem);
} else {
if (!itemMap[pid]) {
itemMap[pid] = {
children: [],
}
}
itemMap[pid].children.push(treeItem)
}
}
return result;
}
2.遞歸
function translateDataToTreeAllTreeMsg (data, parentKey, parentIDKey) {
let parent = data.filter((value) => Number(value[parentKey]) <= 0);// 父數(shù)據(jù)
let children = data.filter((value) => Number(value[parentKey]) > 0);// 子數(shù)據(jù)
let translator = (parent, children) => {
parent.forEach((parent) => {
parent.children = [];
children.forEach((current, index) => {
if (current[parentKey] === parent[parentIDKey]) {
const temp = JSON.parse(JSON.stringify(children));
temp.splice(index, 1);
translator([current], temp);
typeof parent.children !== "undefined"
? parent.children.push(current)
: (parent.children = [current]);
}
});
});
};
translator(parent, children);
return parent;
}
輸出
微信截圖_20220808153617.png