Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

代码如下,不知道如何写递归

data.forEach((item, index) => {
  arr.push({
    id: item.id,
    label: item.name,
    disabled: false,
    children: []
  })
  if (item.list.length > 0) {
    item.list.forEach((item2, index2) => {
      arr[index].children.push({
        id: item.id + '-' + item2.id,
        label: item2.name,
        disabled: false,
        children: []
      })
      if (item2.list.length > 0) {
        item2.list.forEach((item3, index3) => {
          arr[index].children[index2].children.push({
            id: item.id + '-' + item2.id + '-' + item3.id,
            label: item3.name,
            disabled: false,
            children: []
          })
        })
      }
    })
  }
})

注意id部分item.id + '-' + item2.id + '-' + item3.id
不晓得这样的嵌套,递归方法怎么写


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

1 Reply

0 votes
by (71.8m points)

不晓得是不是这个意思

 const arrs = [{id:1, label:"测试",list:[{id:11, label:"测试1-1",list:[{id:111, label:"测试1-1-1"}]}]}]
    const func = (arr, sufix='') => {
      return arr.map(item => {
        const id = sufix?`${sufix}-${item.id}`:item.id
        const res = {
          id,
          label:item.label,
        }
        if(item.list) res.children = func(item.list, `${id}`)
        return res
      })
    }
    console.log(func(arrs))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...