js树形结构和线性结构相互转换

623 阅读1分钟

对扁平化数据转换成树形结构,或者将树形结构转为扁平化数据。常处理菜单。

一、树形结构数据扁平化数组

const treeTolist = (tree, childrenProp = "children", clone = true) => {  if (!isArray(tree)) {    tree = [tree];  }  let list = [];  let newTree = clone ? clone(tree) : tree;  newTree.forEach((item) => {    list.push(item);    const childrenNodes = item[childrenProp];    if (childrenNodes && childrenNodes.length) {      list = [...list, ...treeTolist(childrenNodes, childrenProp), false];    }  });  list.forEach((item) => {    delete item[childrenProp];  });  return list;};

二、线性结构数据转换树形结构数据

const listToTree = (  list = [],  parentId = "0",  childrenProp = "children",  parentProp = "parentId",  idprop = "id") => {  let nodes = clone(list).filter((item) => item[parentProp] === parentId);  nodes.forEach((item) => {    if (!item[idprop]) {      throw new Error(idProp + "属性不允许为空");    }    let childrenNodes = listToTree(      list,      item[idprop],      childrenProp,      parentProp,      idProp    );    if (childrenNodes && childrenNodes.length) {      item[childrenProp] = childrenNodes;    }  });  return nodes;};