一、定义一个嵌套子级数组
const arr = [{
id:1,
key: "411200000000",
label: "三门峡市",
children: [{
key: "11411200005802248U",
label: "三门峡市水利局"
}, {
key: "11411200005802264H",
label: "三门峡市林业局"
}, {
key: "114112000058023445",
label: "三门峡市生态环境局"
}]
}, {
id:2,
key: "1000111",
label: "自有机构",
children: []
}]
二、定义递归函数
function changeCascader(key, arrData) {
let arr = [];
let returnArr = []; // 存放结果的数组
let depth = 0; // 定义全局层级
// 定义递归函数
function childrenEach(childrenData, depthN) {
for (var j = 0; j < childrenData.length; j++) {
depth = depthN; // 将执行的层级赋值 到 全局层级
arr[depthN] = childrenData[j].key;
if (childrenData[j].key == key) {
returnArr = arr.slice(0, depthN + 1); //将目前匹配的数组,截断并保存到结果数组,
break;
} else {
if (childrenData[j].children) {
depth++;
childrenEach(childrenData[j].children, depth);
}
}
}
return returnArr;
}
return childrenEach(arrData, depth);
}
三、定义一个新数组
let newArr = []
四、获取子级id
let keyString = "11411200005802248U"
五、将子级id转成字符串数组
let key = keyString.split(',')
六、对转换成数组的子id进行遍历,然后利用递归求出父id添加到新数组中
for (let i in key) {
newArr.push(
changeCascader(key[i],arr)
)
}
console.log(newArr)
注意:
这里的子数组为children,如果子数组是其它字段,则需要把递归函数中的children替换