JayMo
  • 4
  • 新人请关照

把 list 转换成树形结构

实现一个convert函数实现下面的需求,要求支持多级(可以根据list,实现4级5级以及尽可能降低时间复杂度)

==========)


// ["一级品类", "二级品类", "三级品类"]
let list = [

    ["个护", "全身", "止汗"],
    ["个护", "全身", "身体乳液"],
    ["个护", "全身", "身体护理套装"],
    ["个护", "全身", "身体磨砂"],
    ["彩妆", "唇部", "唇线"],
    ["彩妆", "唇部", "唇膏"],
    ["彩妆", "唇部", "唇部妆前定妆"],
    ["彩妆", "唇部", "唇釉"],
    ["彩妆", "彩妆套装", "彩妆套装"],
    ["彩妆", "眼部", "眉妆"],
]

const result = convert(list, ...);

// 转换后的结果如下
let result = [

{
    'name':'个护',
    'children': [
        {
            'name': '全身',
            'children': [
                {
                    'name':'止汗'
                },
                {
                    'name': '身体乳液'
                }
                ...
            ]
        }
    ]
}
...

]

阅读 119
评论 2019-12-05 提问
    1 个回答
    gaoryrt
    • 2.6k
    const fn = list => {
        let rtn = []
        list.forEach(arr => {
            let p = rtn
            arr.forEach((name, level) => {
                if (p.map(item => item.name).indexOf(name) < 0) p.push({ name })
                const index = p.map(item => item.name).indexOf(name)
                if (level === arr.length - 1) return
                if (!p[index].children) p[index].children = []
                p = p[index].children
            })
        })
        return rtn
    }
    console.log(JSON.stringify(fn(list), '  ', 2))
    [
      {
        "name": "个护",
        "children": [
          {
            "name": "全身",
            "children": [
              {
                "name": "止汗"
              },
              {
                "name": "身体乳液"
              },
              {
                "name": "身体护理套装"
              },
              {
                "name": "身体磨砂"
              }
            ]
          }
        ]
      },
      {
        "name": "彩妆",
        "children": [
          {
            "name": "唇部",
            "children": [
              {
                "name": "唇线"
              },
              {
                "name": "唇膏"
              },
              {
                "name": "唇部妆前定妆"
              },
              {
                "name": "唇釉"
              }
            ]
          },
          {
            "name": "彩妆套装",
            "children": [
              {
                "name": "彩妆套装"
              }
            ]
          },
          {
            "name": "眼部",
            "children": [
              {
                "name": "眉妆"
              }
            ]
          }
        ]
      }
    ]
    [Finished in 0.1s]
    评论 赞赏 2019-12-05
      社区建设
      合作问答

      欢迎来到 SegmentFault 0x 社区建设。这里可以讨论有关 SegmentFault 的一切,帮助我们改进产品、完善社...