中国领先的工业平台

返回贤集网 返回微头条
贤集网技术微头条APP获取

递归查找树形结构路径

 山东大明消毒科技有限公司

下载贤集网APP入驻自媒体

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)

})

复制代码



最新回复

还没有人回复哦,抢沙发吧~

发布回复

为您推荐

热门交流