chenhuiYj / chenhuiYj/note

练习题9:根据 key 记录 tree 层级路径

Open
#20 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
HTML
Stars
6
Forks
0
PR merge metrics
No merged PRs in 30d

Description

比如给出一个数据

{
    key:1,
  children:[{
     key:2,
     children:null
  }]
}

需要根据key记录每一项对应的层级路径,如上面的数据。需要返回 {1:'1',2:'1-2'}

实现这个思路本质上就是写一个递归,只是多了一个,每次传入的不止是数据,还有层级路径

demo 数据

let arr=[
{
    key:1,
    children:[
        {
            key:2,
            children:[{
                key:3,
                children:null

            }]
        },
        {
            key:6,
            children:[{
                key:7,
                children:null
            
            }]
        }
    ]

},
{
    key:'4',
    children:[{
        key:'5',
        children:null
        
    }]
}]

实现代码

function getPaths(list){
    let result={}
    function handle(data,path){
        for(let item of data){
            result[item.key]=path?path+'-'+item.key:path+item.key
            if(item.children){
                handle(item.children,result[item.key])
            } 
        }
    }
    handle(list,'')
    return result
}

测试结果

let keys=getPaths(arr)
console.log(keys)

// {1: "1", 2: "1-2", 3: "1-2-3", 4: "4", 5: "4-5", 6: "1-6", 7: "1-6-7"}

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

No repository file or test is named. Start by reviewing the getPaths example and demo data in the issue; the expected output and implementation are already provided, so confirm whether any documentation entry is still needed and what repository location should contain it.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript
Domain
documentation
Issue type
Documentation
Difficulty
1/5
Estimated time
Under an hour
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.