递归回溯算法解决需求

由data改成

[ {"class_1"=>"12345","class_2":"12345","class_3":"1224","spu_id":24324,"class_1_name"=>"分类1","class_2_name":"分类二","class_3_name":"分类三"}, {"class_1"=>"12345","class_2":"12345","class_3":"1224","spu_id":24324,"class_1_name"=>"分类1","class_2_name":"分类二","class_3_name":"分类三"}



let data = 
    [
      {
        "id":"f660a8ca-cb18-4c7d-af2e-24fe8f18fd3a",
        "name":"一级标题1",
        lavel:1,
        "items":[
          {
            "id":"90970f4c-af7e-4d2b-8151-eb6a813342d3",
            "name":"二级标题1-1",
            lavel:2,
            "items":[
              {
                "id":"e3ed9083-4283-47d6-87f6-5e39e14f8bb8",
                "name":"三级标题1-1-1",
                "ImgSrc":"",
                "items":[],
                lavel:3
              },
              {
                "id":"400ab4b4-1a73-4753-b3c6-7c47e0336b72",
                "name":"三级标题1-1-2",
                "ImgSrc":"https://xesbook-static-test.oss-cn-beijing.aliyuncs.com/source/static/image/20200414/蛋糕女孩.jpg",
                "items":[],
                lavel:3
              }
            ]
          },
          {
            "id":"7efb0051-868d-49bf-b2ad-32087cc91a3c",
            "name":"二级标题1-2",
            "items":[],
            lavel:2,
          }
        ]
      },
      {
        "id":"7cacfbd3-f13f-4c76-91b3-d77741ee4664",
        "name":"一级标题2",
        "items":[],
        lavel:1,
      }
    ]
    function recurTree(data) {
      let res = []
      
      function findPath(res, list, path){
        console.log(list)
       
        // if(list.lavel == 3 ) {
        //   path.push({class_3: list.id})
        //   res.push(path)
        //   return
        // }
        console.log(list.items)
        if(list.items.length == 0) {
          res.push(path)
          return
        }
        // console.log(clear)
        for(let i = 0;i < list.items.length; i++) {
          let child = list.items[i]
         
          if(child.lavel == 2) {
            path.push({class_2: child.id})
          }
          if(child.lavel == 3 ) {
            path.push({class_3: child.id})
            // break
          }
          findPath(res, child, path.slice())
             path.pop()
        }
      }
      for (let index = 0; index < data.length; index++) {
        let path = []
        if(data[index].lavel == 1) {
          path.push({class_1: data[index].id})
        }
        findPath(res, data[index], path.slice())
      }
      return res
    }
console.log("recurTree",recurTree(data)
)
发布了238 篇原创文章 · 获赞 91 · 访问量 44万+

猜你喜欢

转载自blog.csdn.net/qq_34629352/article/details/105517319