Skip to content

树结构中寻找指定元素(根据id之类的唯一标识)的路径 #30

@Rain120

Description

@Rain120

题目

const data = {
    key: '1',
    id: 'q',
    children: [
        {
            key: '1.1',
            id: 'w',
            children: [
                {
                    key: '1.1.1',
                    id: 'f',
                    children: [],
                },
                {
                    key: '1.1.2',
                    id: 'd',
                    children: [
                        {
                            key: '1.1.2.1',
                            id: 'a',
                            children: [],
                        },
                    ],
                },
            ],
        },
        {
            key: '1.2',
            id: 'x',
            children: [],
        },
        {
            key: '1.3',
            id: 'b',
            children: [],
        },
        {
            key: '1.4',
            id: 'j',
            children: [
                {
                    key: '1.1.2',
                    id: 'k',
                    children: [
                        {
                            key: '1.1.2.1',
                            id: 't',
                            children: [],
                        },
                    ],
                },
                {
                    key: '1.1.2',
                    id: 'i',
                    children: [
                        {
                            key: '1.1.2.1',
                            id: 'o',
                            children: [],
                        },
                    ],
                },
                {
                    key: '1.1.2',
                    id: 'g',
                    children: [
                        {
                            key: '1.1.2.1',
                            id: 'ad',
                            children: [],
                        },
                    ],
                },
            ],
        },
    ],
};

const getPosByIdInTree = (tree, id) => {
   // ...
};

let source = 'ad';
let pos = getPosByIdInTree(data, source);
// ad: 0,3,2,0
console.log(source + ': ' + pos);
source = 'f';
pos = getPosByIdInTree(data, source);
// f: 0,0,0
console.log(source + ': ' + pos);
source = 'x';
pos = getPosByIdInTree(data, source);
// x: 0,1
console.log(source + ': ' + pos);

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions