前端 - 求助,数据转换,.字符串转为children格式?

 

问题描述:

有如下数据

[
  {
    "addData": "item1.child1"
  },
  {
    "addData": "item1.child2"
  },
  {
    "addData": "item1.child3"
  },
  {
    "addData": "item2"
  },
  {
    "addData": "item3"
  },
  {
    "addData": "item4.child1"
  },
  {
    "addData": "item4.child2.key1"
  },
  {
    "addData": "item4.child2.key2"
  },
  {
    "addData": "item4.child3"
  }
]

需转为下面的格式

[
  {
    "value": "item1",
    "label": "item1",
    "children": [
      {
        "value": "child1",
        "label": "child1"
      },
      {
        "value": "child2",
        "label": "child2"
      },
      {
        "value": "child3",
        "label": "child3"
      }
    ]
  },
  {
    "value": "item2",
    "label": "item2"
  },
  {
    "value": "item3",
    "label": "item3"
  },
  {
    "value": "item4",
    "label": "item4",
    "children": [
      {
        "value": "child1",
        "label": "child1"
      },
      {
        "value": "child2",
        "label": "child2",
        "children": [
          {
            "value": "key1",
            "label": "key1"
          },
          {
            "value": "key2",
            "label": "key2"
          }
        ]
      },
      {
        "value": "child3",
        "label": "child3"
      }
    ]
  }
]

大概就是' . '分割的字符串重新组成 value label 树形结构,. 字符串分割数目不固定,求大佬解惑


 

第 1 个答案:

使用递归就行了, 常见算法:
image.png

console.log(convertData([
    {
      "addData": "item1.child1"
    },
    {
      "addData": "item1.child2"
    },
    {
      "addData": "item1.child3"
    },
    {
      "addData": "item2"
    },
    {
      "addData": "item3"
    },
    {
      "addData": "item4.child1"
    },
    {
      "addData": "item4.child2.key1"
    },
    {
      "addData": "item4.child2.key2"
    },
    {
      "addData": "item4.child3"
    }
  ]))
  function convertData (originalData) {
    const result = [];

    for (let item of originalData) {
      const parts = item.addData.split('.');
      let parent = result;
      // 遍历该项数据的所有部分
      for (let part of parts) {
        // 在当前父级节点的子节点中查找该部分
        let current = parent.find(node => node.value === part);

        if (!current) {
          // 如果该部分不存在,则创建新的节点,并将其添加到当前父级节点的子节点中
          current = {
            value: part,
            label: part
          };

          parent.push(current);
        }
        // 更新父级节点引用为当前节点,继续处理下一个部分
        parent = current.children || (current.children = []);
      }
    }

    return result;
  }

跟做项目时,数据交互部分的接口是别人提供,我换成apifox的也可以获取到模拟数据,但是这两天又跟了一个项目有登录功能,我试着用接口请求方式是post,也可以在控制台获得数据但那是我定义 ...