常用utils工具函数合集

62 阅读1分钟

1. 数组转树结构方法

/**
 * 递归查找添加children
 * @param {数组数据} data
 * @param {存放返回结果} result
 * @param {父id} pid
 */
function getChildren(data, result, pid) {
  for (const item of data) {
    if (item.parentId === pid) { // 注意切换判断父子属性的对象属性
      const newItem = { children: [], ...item };
      result.push(newItem);
      getChildren(data, newItem.children, item.id);
    }
  }
}
/**
 * 转化方法
 * @param {数组数据} data 
 * @param {父id} pid 
 * @returns 
 */
function arrayToTree(data, pid) {
    let result = []
    getChildren(data, result, pid)
    return result
}

遍历传递数组,利用对象的地址引用修改传入的result,pid使得数组分级添加children属性,在多次遍历后根据parentId属性生成树结构的数据。

总结

持续学习,记录一下。