Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
647 views
in Technique[技术] by (71.8m points)

多个数组 怎么转为树形结构 并需要去重

例: ['动物-昆虫-蚂蚁', '动物-昆虫-蝴蝶', '植物-草-绿色', '植物-花-红色']`
想得到:
[
{
name:'动物',
children:[

{name:'昆虫'
    children:[
        {name:'蚂蚁'},
        {name:'蝴蝶'}
    ]
}

]
},
{
同上
}
]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
function listToTree (srcList) {
  let destList = []
  srcList.forEach(path => {
    let pathList = path.split('-')
    let levelList = destList
    for (let name of pathList) {
      let obj = levelList.find(item => item.name == name)
      if (!obj) {
        obj = { name, children: [] }
        levelList.push(obj)
      }
      levelList = obj.children
    }
  })
  return destList
}

测试:

let srcList =  ['动物-昆虫-蚂蚁', '动物-昆虫-蝴蝶', '植物-草-绿色', '植物-花-红色']
let result = listToTree(srcList)
console.log(JSON.stringify(result, null, 2))

输出:

[
  {
    "name": "动物",
    "children": [
      {
        "name": "昆虫",
        "children": [
          {
            "name": "蚂蚁",
            "children": []
          },
          {
            "name": "蝴蝶",
            "children": []
          }
        ]
      }
    ]
  },
  {
    "name": "植物",
    "children": [
      {
        "name": "草",
        "children": [
          {
            "name": "绿色",
            "children": []
          }
        ]
      },
      {
        "name": "花",
        "children": [
          {
            "name": "红色",
            "children": []
          }
        ]
      }
    ]
  }
]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...