ITPub博客

首页 > IT职业 > IT图书 > 递归查找树形结构路径

递归查找树形结构路径

IT图书 作者:yxl1108 时间:2021-09-09 09:14:01 0 删除 编辑
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 

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/3158/viewspace-2808796/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-30

  • 博文量
    82
  • 访问量
    492