js把树形结构数据列表化

原始数据

 let arr = [
        {
          name: "a",
          children: [
            { name: "a-1", children: [{ name: "a-1-1" }, { name: "a-1-2" }] },
            { name: "a-2", children: [{ name: "a-2-1" }, { name: "a-2-2" }] },
          ],
        },
        {
          name: "b",
          children: [
            {
              name: "b-1",
              children: [{ name: "b-1-1", children: [{ name: "b-1-1-1" }] }],
            },
          ],
        },
        {
          name: "c",
        },
      ];

想要的数据结构

js把树形结构数据列表化_第1张图片

废话不多说,直接上方法

  processData(treeData = []) {
      let max = 0;
      let datasource = [];
      let source = [];
      function each(data = [], floor) {
        data.forEach((e) => {
          e.floor = floor;
          source[floor - 1] = e.name;
          source.splice(floor, source.length - 1);
          if (floor > max) {
            max = floor;
          }
          if (e.children && e.children.length > 0) {
            each(e.children, floor + 1);
          } else {
            datasource.push([...source]);
          }
        });
      }
      each(treeData, 1);
      let arr = [];
      if (max > 0) {
        for (let i = 1; i <= max; i++) {
          arr.push(`${i}级菜单`);
        }
      }
      return [arr, ...datasource];
    },

看不懂的留言找我,就不详细备注了

你可能感兴趣的:(javascript,数据结构,前端,js,算法)