递归查找树形结构路径
标签:
JavaScript
var obj = {
"name": "河北省",
"code": "130000",
"child": [{
"name": "石家庄市",
"code": "130100",
"child": [{
"name": "长安区",
"code": "130102"
}, {
"name": "桥东区",
"code": "130103"
}]
}, {
"name": "唐山市",
"code": "130200",
"child": [{
"name": "路南区",
"code": "130202"
}, {
"name": "路北区",
"code": "130203"
}]
}]
}
/**
* 递归查找树形结构路径
*
* @param {any} id 查找路径结尾的字段值
* @param {any} catalog 目标对象
* @param {string} [compareAttr='id'] 与查找路径结尾字段值对比的属性字段名,默认为id
* @param {string} [childAttrs=['child']] 每级的子节点集合的字段名
* @returns Promise resolve包含查找路径上每一级的对象信息
*/
function getPathById (id, catalog, compareAttr = 'id', childAttrs = ['child']) {
return new Promise(function (resolve, reject) {
if (!catalog || Object.prototype.toString.call(catalog) !== "[object Object]") {
console.error('目标对象不存在或格式错误,catalog为非数组对象,如:{}')
return reject()
}
var path = [];
try {
function getNodePath(node) {
path.push(node);
if (node[compareAttr] == id) {
throw('GOT it')
}
var children;
childAttrs.forEach(V => {
if (children) return
children = node[V]
})
if (children && children.length > 0) {
for (var i = 0; i < children.length; i++) {
getNodePath(children[i]);
}
path.pop()
} else {
path.pop()
}
}
getNodePath(catalog);
} catch (e) {
resolve(path)
}
})
};
getPathById('130202', obj, 'code').then(function(res) {
console.log(res)
})
点击查看更多内容
1人点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦