js 递归查找属性值 (根据某个属性值查找另一个属性值)

var defaultData = [{
text: '开发部门',
href: '#parent1',
tags: ['4'],
id:3003,
nodes: [
{
text: 'Child 1',
href: '#child1',
tags: ['2'],
id:3004,
nodes: [
{
text: 'Grandchild 1',
href: '#grandchild1',
tags: ['0'],
id:3005,
},
{
text: 'Grandchild 2',
href: '#grandchild2',
tags: ['0'],
id:3006,
}
]
},
{
text: 'Child 2',
href: '#child2',
tags: ['0'],
id:3007,
}
]
},
{
text: '产品部门',
href: '#parent2',
tags: ['0'],
id:3008,
nodes: [
{
text: '产品Child 1',
href: '#child1',
tags: ['2'],
id:3009,
nodes: [
{
text: '产品Grandchild 1',
href: '#grandchild1',
tags: ['0'],
id:30010,
}
]
},
{
text: '产品Child 2',
href: '#child2',
tags: ['0'],
id:30011,
}
]
},
{
text: '销售部门',
href: '#parent3',
tags: ['0'],
id:30012,
},
{
text: '运营部门',
href: '#parent4',
tags: ['0'],
id:30013,
},
{
text: '设计部门',
href: '#parent5' ,
tags: ['0'],
id:30014,
}];
var tarText = "Grandchild 1";
function findTargetId(dataobj,targetText){
if(dataobj.text == targetText){
return dataobj.id;
}else{
if(dataobj.nodes!=null){
for(var i=0; i<dataobj.nodes.length; i++){
var flagId = findTargetId(dataobj.nodes[i],targetText);
if(flagId){
return flagId;
}
}
}
}
return false;
}
for(var i=0;i<defaultData.length;i++){
var flag = findTargetId(defaultData[i],tarText)
if(flag){
result = flag;
}

}
console.log(result)

上一篇:Git推送里程碑tag到远程仓库方法


下一篇:项目二进制标位实战应用