JS树形结构数据,根据子节点数据获取所有父节点数据
省市区多维数组通过value=130628 获取到 ["河北省", "保定市", "高阳县"]函数调用这样就可以根据子节点数据获取所有父节点数据啦
·
省市区多维数组
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);
// ["河北省", "保定市", "高阳县"]
这样就可以根据子节点数据获取所有父节点数据啦
更多推荐
已为社区贡献13条内容
所有评论(0)