[英]Using aimaraJS for tree structure creation how to get the specific node selected for performing API action?
[英]How to get the value of each node of the tree structure
一个嵌套的arrays和对象数组,每个节点都有一个唯一的值,在这个数据上找一个值,如何获取每个节点上的值?
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 可以使用 function 递归遍历 object 结构,如下所述:
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']
你能解释一下为什么你会这样吗?
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)
你可以使用dfs算法
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.