Today, a flat array of the topic, small preparation of two schemes, welcome you to participate in the comments can write more better methods for everyone to reference learning and communication.

  • This article participated in the nuggets surrounding gifts 🎁 campaignJust leave your thoughts and thoughts in the comments section, or talk about other topics such as how to learn fast, what books I recommend, what I would like to say to someone new, or write a poemThe deadline is 12 noon on December 12
  • The two users with the most likes in the comments section of this article will receive nuggetsThe new badge
  • If this article reviews the comprehensive heat in activityTop 1-5Will getNew badge 1 set 或 Nuggets new IPT Shirt 1 piece
  • Get involved, guys

Title: The following data is processed into a multi-layer tree structure with only one layer of children

data = [
  {
    name: "About".path: "/about".children: [{name: "About US".path: "/about/us"
      },
      {
        name: "About Comp".path: "/about/company".children: [{name: "About Comp A".path: "/about/company/A".children: [{name: "About Comp A 1".path: "/about/company/A/1"}]}]}]// The structure after processing[{name: "About".path: "/about".children: [{name: "About US".path: "/about/us"
      },
      {
        name: "About Comp".path: "/about/company"}, {name: "About Comp A".path: "/about/company/A"
      },
      {
         name: "About Comp A 1".path: "/about/company/A/1"}}]]Copy the code

Code implementation:

Methods a

// Recursive traversal implementation
var recursiveFunction4 = function(){
    var aa=[]
    const getStr = function(data){
        data.forEach(item= > {
        aa.push({
            name: item.name,
            path: item.path
        })
        if(item.children? .length){let children=getStr(item.children)
        }
    })
    }
    getStr(data[0].children)
    / /... Expand operator because the first two items are the same and just copy them and replace the last item with children
    aa= [{...data[0].children:aa}]
    console.log(aa)
}
recursiveFunction4()// Optimization based on recursiveFunction3()
Copy the code

Method 2

// Write a code that can freely define a flat level, level code is not flat level
function flatTree(data, level = 0, index = 0){
    let result = [], obj;
    data.forEach(item= > {
        result.push(obj = {
            name: item.name,
            path: item.path
        })
        
        if(item.children? .length){let children = flatTree(item.children, level, index + 1)
            if(level > index){
                obj.children = children
            }else{
                result = result.concat(children)
            }
        }
    })
    return result
}
Copy the code