List和Tree数据之间相互转换

对于大部分开发有一种需求,是将list转换为tree结构,或者将tree转为list结构,下面针对不同的需求分别简单介绍不同的转换方法

1. list转为tree
从后台获取的list数据:

let refs = [
 { "id": "ckb696kne0001lj3dejycrvew","ip": "192.188.1.112", "parentIp": null },
 { "id": "ckb698ybv0002lj3d19qp8a40", "ip": "172.21.45.97", "parentIp": "192.188.1.112"},
 { "id": "ckb699pvf0005lj3da9uqxgoy", "ip": "192.188.1.108","parentIp": "192.188.1.112" },
 { "id": "ckb69b1070009lj3d1o39j8uc", "ip": "192.188.1.111", "parentIp": "192.188.1.108" },
 { "id": "ckb69bpoh0012lj3dfq7d2ns4","ip": "192.188.1.109", "parentIp": "192.188.1.111"},
 { "id": "ckb69clw90014lj3doet59ntt",  "ip": "128.0.3.7","parentIp": "192.188.1.108" },
 {  "id": "ckb69d7680015lj3dss5fhoo9", "ip": "128.0.3.8", "parentIp": "128.0.3.7"},
 {  "id": "ckcwpe75300151bkf4fourifa", "ip": "192.168.1.33", "parentIp": "128.0.3.7" }
]

但是在实际的UI展示需要生成tree形结构数据,方便展示,name就需要有一个方法去实现:

function listToTree(list, parentIp = null) {
  return list.filter(item => item.parentIp === parentIp).map(item => ({
    ...item,
    children: listToTree(list, item.ip)
  }));
}

调用结果如下:
List和Tree数据之间相互转换_第1张图片
2. tree转list
直接利用上面生成的tree数据

function treeToArray(list, newArr = []) {
  list.forEach((item) => {
    const { children } = item;
    if (children) {
      delete item.children;

      if (children.length) {
        newArr.push(item);
        return treeToArray(children, newArr);
      }
    }
    newArr.push(item);
  });
  return newArr;
}

输出结果:
List和Tree数据之间相互转换_第2张图片

你可能感兴趣的:(List和Tree数据之间相互转换)