let currentVal = '1-1-3-2'
let list = [{
text: "1省",
value: "1",
child: [{
text: "1市",
value: "1-1",
child: [{
text: "1区",
value: "1-1-1",
child: [{
text: "1区-1镇",
value: "1-1-1-1",
}, ],
},
{
text: "2区",
value: "1-1-2",
child: [{
text: "2区-1镇",
value: "1-1-2-1",
}, ],
},
{
text: "3县",
value: "1-1-3",
child: [{
text: "3县-1镇",
value: "1-1-3-1",
},{
text: "3县-2镇",
value: "1-1-3-2",
} ],
},
],
}, ],
}, ];
// 根据当前位置 区域
function getDefault(arr, currentVal) {
let data = JSON.parse(JSON.stringify(arr)) // 对传入的参数进行深拷贝
let newData = [] // 创建空数组用来接收操作后的新数组
// 递归 扁平化
const hasChildren = (item, parentItem = {}) => { // 递归遍历,把包含children的选项拿出来,push到之前新建的空数组内
item.parentValue = parentItem.value;
item.child && item.child.length && item.child.forEach(v => {
hasChildren(v, item)
})
delete item.child // 删除原children属性,可选项
newData.push(item)
}
data.forEach(v => hasChildren(v));
let result = []
// 通过递归找到对应父级
const hasParent = (id) => {
newData.forEach(item => {
if (id == item.value) {
result.unshift(item)
if (item.parentValue) {
hasParent(item.parentValue)
}
}
})
}
hasParent(currentVal)
return result
};
let resultArr = getDefault(list, currentVal)
console.log('resultArr',resultArr)// [{},{},{},{}]
tree 数据结构 已知当前值 把他的所有祖先集都拿到一个数组
于 2022-10-13 01:55:52 首次发布