js处理树结构数据-给树节点添加本级数据

2023-07-04  本文已影响0人  甘道夫老矣

场景:需要给数据处理成树结构数据,并把每个 节点添加本级数据

  let obj = {
                    label: "name",
                    value: "id",
                    fatherId: "orgId"
 }
 let data = this.transformTree(arr2, obj);
 //递归处理级联数据fun1
    transformTree = (list: any, obj: any, type: number) => {
        let tree = [];
        for (let i = 0, len = list.length; i < len; i++) {
            if (list[i][obj.fatherId] === '0' || !list[i][obj.fatherId]) {
                  let item = this.queryChildren2(list[i], list, obj);
                    item.title = item[obj.label];
                    item.key = item[obj.value];
                    tree.push(item);
            }
        }
        return tree;
    };
 queryChildren2 = (parent: any, list: any, obj: any) => {
        let children = [];
        for (let i = 0, len = list.length; i < len; i++) {
            if (list[i][obj.fatherId] === parent[obj.value]) {
                let item = this.queryChildren2(list[i], list, obj);
                item.title = item[obj.label];
                item.key = item[obj.value];
                // item.extra=item;
                children.push(item);
            }
        }
        if (children.length) {
            if (parent.isLeaf) {
                delete parent.isLeaf;
            }
//处理本级
            let thisLevel = JSON.parse(JSON.stringify(parent));
            thisLevel.title = '本级--' + thisLevel.name;
            thisLevel.isThisLevel = true;
            thisLevel.isLeaf = true;
            children.unshift(thisLevel)
            parent.children = children;
        } else {
            parent.isLeaf = true;
        }
        return parent;
    }
上一篇 下一篇

猜你喜欢

热点阅读