如何获取树形结构每个节点的值

时间:2019-10-24 09:36:25

标签: javascript algorithm

由嵌套数组和对象组成的数组,每个节点都有一个唯一的值,在此数据上查找值,如何在每个节点上获取该值?

const opts = [
    {
        value: '01',
        children: [
            { value: '0198' },
            { value: '0195', children: [{ value: '09977' }] }
        ]
    },
    {
        value: '02',
        children: [
            { value: '01986' },
            {
                value: '0195',
                children: [
                    { value: '09978', children: [{ value: '09864' }, { value: '90876' }] }
                ]
            }
        ]
    }
];

const code = '90876';
// expected get an array ['02','0195','09978','90876']

3 个答案:

答案 0 :(得分:2)

U可以使用函数像described here那样递归遍历对象结构:

const opts = [
    {
        value: '01',
        children: [
            { value: '0198' },
            { value: '0195', children: [{ value: '09977' }] }
        ]
    },
    {
        value: '02',
        children: [
            { value: '01986' },
            {
                value: '0195',
                children: [
                    { value: '09978', children: [{ value: '09864' }, { value: '90876' }] }
                ]
            }
        ]
    }
];


function eachRecursive(obj, cb) {
    for (var k in obj) {
        if (typeof obj[k] == "object" && obj[k] !== null)
            eachRecursive(obj[k], cb);
        else
            cb(obj[k]);
    }
}

let results = [];

eachRecursive(opts, val => results.push(val));
console.log(results);

但不确定您对评论的意思:// expected get an array ['02','0195','0997','90876']是否可以解释为什么会这样?

答案 1 :(得分:1)

您可以使用dfs算法

dst_t

答案 2 :(得分:0)

const opts = [
    {
        value: '01',
        children: [
            { value: '0198' },
            { value: '0195', children: [{ value: '09977' }] }
        ]
    },
    {
        value: '02',
        children: [
            { value: '01986' },
            {
                value: '0195',
                children: [
                    { value: '09978', children: [{ value: '09864' }, { value: '90876' }] }
                ]
            }
        ]
    }
];
console.log(opts[1].value)
console.log(opts[1].children[1].value)
console.log(opts[1].children[1].children[0].value)
console.log(opts[1].children[1].children[0].children[1].value)