js常用方法

90 阅读1分钟

1.转化为树形-多维 juejin.cn/post/695874…

newArrFn(arr, rootValue = 0) {
      let temp = []
      return arr.reduce((acc, cur) => {
        console.log('accaccacc', acc)
        console.log('curcurcurcurcur------------------', cur)
        if (cur.p_id === rootValue) {
          temp = cur
          const children = this.newArrFn(arr, cur.id)
          if (children.length) {
            temp.children = children
          }
          acc.push(temp)
        }
        return acc
      }, [])
    },
    
     const filterArray = (list: any, parentId: any) => {
      let tree = [];
      let temp;
      for (let i = 0; i < list.length; i++) {     
        if(list[i].pid===parentId){
         let obj=list[i]
         temp = filterArray(list, list[i].id);
         if (temp.length > 0) {
          obj.children = temp;
        }
         tree.push(obj);
        }
      }
      return tree;
    };