省市区多维数组

const cities = [
  {
    "value": "13",
    "text": "河北省",
    "children": [
      {
        "value": "1306",
        "text": "保定市",
        "children": [
          {
            "value": "130602",
            "text": "竞秀区"
          },
          {
            "value": "130606",
            "text": "莲池区"
          },
          {
            "value": "130607",
            "text": "满城区"
          },
          {
            "value": "130608",
            "text": "清苑区"
          },
          {
            "value": "130609",
            "text": "徐水区"
          },
          {
            "value": "130628",
            "text": "高阳县"
          },
          {
            "value": "130636",
            "text": "顺平县"
          }
        ]
      }
    ]
  }
]

通过value=130628 获取到 ["河北省", "保定市", "高阳县"]

函数

/**
 * 显示层级数据
 * @param tree {Array} 树数据
 * @param func {Function} 回调函数
 * @param field {String} 字段名称
 * @param path {Array} 路径数据
 * @returns {*[]|[]|*}
 */
function treeFindPath(tree, func, field = "", path = []) {
  if (!tree) return []
  for (const data of tree) {
    field === "" ? path.push(data) : path.push(data[field]);
    if (func(data)) return path
    if (data.children) {
      const findChildren = treeFindPath(data.children, func, field, path)
      if (findChildren.length) return findChildren
    }
    path.pop()
  }
  return []
},

调用

const cId = "130628";
let arr = this.treeFindPath(cities, data => data.value === cId, "text");
console.log(arr);
// ["河北省", "保定市", "高阳县"]

这样就可以根据子节点数据获取所有父节点数据啦

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐