关于javascript:树形数据转换

46次阅读

共计 1031 个字符,预计需要花费 3 分钟才能阅读完成。

1、树形数据转数组

 const recursion = (arr, num) => {arr.forEach((ele) => {
    // 判断有子元素, 并且子元素的长度大于 0 就再次调用本身
    if (ele.children && ele.children.length > 0) {// var node_root = ele.children.filter((item) => item.basicData == 3);
      for (let k = 0; k < ele.children.length; k++) {if (ele.children[k].basicData == 3) {
          data.rootAllNode.push({nodeId: ele.children[k].id,
            context: ele.children[k].title,
            parentId: ele.children[k].parentId,
            basicData: ele.children[k].basicData,
            checkArr: "1",
            checked: "1",
            disabled: true,
          });
        } else if (ele.children[k].basicData == 2) {
          data.parentAllNode.push({nodeId: ele.children[k].id,
            context: ele.children[k].title,
            parentId: 1,
            basicData: ele.children[k].basicData,
            checkArr: "1",
            checked: "1",
            disabled: true,
          });
        }
      }
      recursion(ele.children, num);
    }
  });
};

2、数组转树形数据

const toTree = (data) => {let result = [];

  if (!Array.isArray(data)) {return result;}
  data.forEach((item) => {delete item.children;});
  let map = {};
  data.forEach((item) => {map[item.nodeId] = item;
  });
  data.forEach((item) => {let parent = map[item.parentId];
    if (parent) {(parent.children || (parent.children = [])).push(item);
    } else {result.push(item);
    }
  });

  return result;
};

正文完
 0