DWQA QuestionsCategory: ProgramHow to traverse an array with such a tree structure
How to be elegant asked 2 months ago

For an array with a tree structure like this, I want to replace all names with titles. How can I traverse it. The level of the array is variable, and there may be some without children in it.

const treeData = [{
    title: '0-0',
    key: '0-0',
    children: [{
      title: '0-0-0',
      key: '0-0-0',
      children: [
        { title: '0-0-0-0', key: '0-0-0-0' },
        { title: '0-0-0-1', key: '0-0-0-1' },
        { title: '0-0-0-2', key: '0-0-0-2' },
      ],
    }, {
      title: '0-0-1',
      key: '0-0-1',
      children: [
        { title: '0-0-1-0', key: '0-0-1-0' },
        { title: '0-0-1-1', key: '0-0-1-1' },
        { title: '0-0-1-2', key: '0-0-1-2' },
      ],
    }, {
      title: '0-0-2',
      key: '0-0-2',
    }],
  }, {
    title: '0-1',
    key: '0-1',
    children: [
      { title: '0-1-0-0', key: '0-1-0-0' },
      { title: '0-1-0-1', key: '0-1-0-1' },
      { title: '0-1-0-2', key: '0-1-0-2' },
    ],
  }, {
    title: '0-2',
    key: '0-2',
    children: []

  }];
4 Answers
Sky shadow answered 2 months ago

Recursive traversal

function setName(obj){
       for(var i in obj){
           obj[i].name = obj[i].title;
           if(obj[i].chilren){
               setName(obj[i].children)
           }
       }
       console.log(obj);
  }
  setName(treeData)
tassels answered 2 months ago
function treedata(a){
            let d=a.map(r=>{
            if(r.children){
                 return {'name':r.title,'key':r.key,'children':treedata(r.children)}
            }else{
                return {'name':r.title,'key':r.key}
            }
          })
          return d
        }
        console.log(treedata(treeData))
Cao Cong answered 2 months ago
JSON.parse(JSON.stringify(treeData).replace(/"title"/g,'"name"'))

If it’s just this simple structure in the title, it’s a lazy way

exponent replied 2 months ago

Magic ideas..

xltsean replied 2 months ago

Yeah, ha ha ha, it’s amazing

krun answered 2 months ago

Where can I find it?name?