-
方案一
export const generateTree = (data, id = 'id', parentId = 'parentId') => {
var result = [];
var idMap = {};
for (var i = 0; i < data.length; i++) {
idMap[data[i][id]] = data[i];
}
for (var i = 0; i < data.length; i++) {
if (idMap[data[i][parentId]] && data[i][id] !== data[i][parentId]) {
if (!idMap[data[i][parentId]]['children']) {
idMap[data[i][parentId]]['children'] = [];
}
if (!idMap[data[i][parentId]]['_level']) {
idMap[data[i][parentId]]['_level'] = 1;
}
data[i]['_level'] = idMap[data[i][parentId]]._level + 1;
idMap[data[i][parentId]]['children'].push(data[i]);
} else {
result.push(data[i]);
}
}
return result;
}
-
方案二
const getChildren = (data) => {
return function (item) {
const arr = [];
data.forEach((value) => {
if (value.pId === item.id) {
arr.push(value);
}
});
return arr;
};
};
export const generateTree = (data) => {
const arr = [];
data.map((item) => {
const list = getChildren(data)(item);
if (list.length > 0) {
item["children"] = list;
}
if (item.pId === 0) {
arr.push(item);
}
});
return arr;
};