查看: 1083|回复: 0

[JavaScript/JQuery] 递归查找树形结构路径

发表于 2018-5-12 08:00:02
  1. var obj = {
  2. "name": "河北省",
  3. "code": "130000",
  4. "child": [{
  5. "name": "石家庄市",
  6. "code": "130100",
  7. "child": [{
  8. "name": "长安区",
  9. "code": "130102"
  10. }, {
  11. "name": "桥东区",
  12. "code": "130103"
  13. }]
  14. }, {
  15. "name": "唐山市",
  16. "code": "130200",
  17. "child": [{
  18. "name": "路南区",
  19. "code": "130202"
  20. }, {
  21. "name": "路北区",
  22. "code": "130203"
  23. }]
  24. }]
  25. }
  26. /**
  27. * 递归查找树形结构路径
  28. *
  29. * @param {any} id 查找路径结尾的字段值
  30. * @param {any} catalog 目标对象
  31. * @param {string} [compareAttr='id'] 与查找路径结尾字段值对比的属性字段名,默认为id
  32. * @param {string} [childAttrs=['child']] 每级的子节点集合的字段名
  33. * @returns Promise resolve包含查找路径上每一级的对象信息
  34. */
  35. function getPathById (id, catalog, compareAttr = 'id', childAttrs = ['child']) {
  36. return new Promise(function (resolve, reject) {
  37. if (!catalog || Object.prototype.toString.call(catalog) !== "[object Object]") {
  38. console.error('目标对象不存在或格式错误,catalog为非数组对象,如:{}')
  39. return reject()
  40. }
  41. var path = [];
  42. try {
  43. function getNodePath(node) {
  44. path.push(node);
  45. if (node[compareAttr] == id) {
  46. throw('GOT it')
  47. }
  48. var children;
  49. childAttrs.forEach(V => {
  50. if (children) return
  51. children = node[V]
  52. })
  53. if (children && children.length > 0) {
  54. for (var i = 0; i < children.length; i++) {
  55. getNodePath(children[i]);
  56. }
  57. path.pop()
  58. } else {
  59. path.pop()
  60. }
  61. }
  62. ?getNodePath(catalog);
  63. } catch (e) {
  64. ? ?resolve(path)
  65. ?}
  66. })
  67. };
  68. getPathById('130202', obj, 'code').then(function(res) {
  69. console.log(res)
  70. })
复制代码


回复

使用道具 举报