JS tree structure commonly used recursive functions [convert parallel arrays to tree, add new levels, handle empty sublevels]

/**
 * 递归将平行数组转换为tree
 * @param {Array} list 需要转换的数组
 * @param {any} parId 默认传0 从第一层开始循环
 * @param {String} parentKey父ID KEY
 */
function createTree(list, parent = '0', parentKey='parentid') {
    
    
    const tree = [];
    list.map((item)=>{
    
    
        if(item[parentKey] === parent ) {
    
    
            // 递归寻找
            item.children = createTree(list, item.id);
            tree.push(item);
        }
    });
    return tree;
}
/**
 * 递归新增层级
 * @param {Array} list 需要处理的数组
 * @param {String} pid 层级键名
 * @param {String} children 子级名称
 */
function addHierarchy (list, pid= 'pid', children = 'children') {
    
    
    if (!Array.isArray(arr)) return []
    const recursion = (arr, index = 0) => {
    
    
        index++
        return arr.map(item => {
    
    
            item[pid] = index
            if (item[children] && item[children].length) recursion(item[children], index)
            return item
        })
    }
    return recursion(list)
}
/**
 * 递归处理空子级
 * @param {Array} list 需要处理的数组
 * @param {String} children 子级名称
 */
function delNullChand(list, children='children') {
    
    
  function recursion(arr) {
    
    
    arr.forEach(item => {
    
    
      if (!item[children].length) {
    
    
        item[children]= null
      } else {
    
    
        recursion(item[children])
      }
    })
    return arr
  }
  return recursion(list)
}

Guess you like

Origin blog.csdn.net/lyf976229437/article/details/123229612