/**
* 数组转换成树形结构
* @param {*} items
*/
const arrayToTree = (items) => {
let result = [],
itemById = {};
// 将数组转换为对象,方便通过 categoryId 查找
items.forEach((item) => {
itemById[item.categoryId] = item;
item.children = [];
if (item.categoryId.length == 3) {
item.parentId = null;
} else if (item.categoryId.length > 3) {
item.parentId = item.categoryId.slice(
-item.categoryId.length,
item.categoryId.length - 3
);
}
});
// 为每个对象添加子对象
items.forEach((item) => {
const parentId = item.parentId;
if (parentId !== null && itemById[parentId]) {
itemById[parentId].children.push(item);
} else {
result.push(item);
}
});
return result;
};
/**
* 获取数组有几层
* @param {*} strItems
*/
function getLevels(strItems, param) {
let maxLevel = 0;
function getLevel(items, level) {
items.forEach((item) => {
if (item[param].length > 0) {
maxLevel = Math.max(maxLevel, level);
getLevel(item[param], level + 1);
} else {
maxLevel = Math.max(maxLevel, level);
}
});
}
getLevel(strItems, 1);
return maxLevel;
}
/**
* 获取子级层数
* @param {*} arr :数组
* @param {*} param :参数
*/
function getLayerArray(arr, param) {
for (let i = 0; i < arr.length; i++) {
if (arr[i][param].length > 0) {
const countSet = getLevels(arr[i][param], param);
arr[i].layer = countSet + 1;
} else {
arr[i].layer = 1;
}
}
return arr;
}
调用:listData是需要处理到数据
// 转换成树的数组
const newList = arrayToTree(listData);
// 获取层级数
const layerArray = getLayerArray(newList, 'children');
将数组转换成树形结构
于 2024-11-27 16:23:22 首次发布