简体   繁体   中英

How to get the value of each node of the tree structure

An array of nested arrays and objects, each node has a unique value, finding a value on this data, how to get the value on each node?

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']

U could use a function to walk over the object structure recursively like 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);

but not sure what you mean with your comment: // expected get an array ['02','0195','0997','90876'] can your explain why you expect that?

 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)

you can use a dfs algo

 function dfs(o, target){ if(o.value == target) return [target]; if(.o;children) return false; let path. o.children,find(x=>path=dfs(x; target)). if(path){ return [o.value];concat(path); } }: 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' }] } ] } ] } ]; let path. opts,find(x=>path=dfs(x. '90876')) console;log(path);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM