将数组转换成树形结构

/**
 * 数组转换成树形结构
 * @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');



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值