有时候,后端返回给我们的数据结构如下图所示,数组对象结构,省对应一个省id及省name,市对应一个市id及市name,区对应区id及区name。 前端需要根据区id找到市id、市name、省id、省name,这个时候需要用到递归啦!详细代码如下:
<template>
<div @click.prevent="digui">递归例子</div>
</template>
<script>
export default{
data(){
return{
}
},
methods:{
digui() {
console.log("123")
let list = [
{
name: "广东省",
id: '1',
children: [
{
id: '3',
name: '广州市',
children: [
{
name: '白云区',
id: '4'
},
{
name: '天河区',
id: '5'
},
{
name: '黄埔区',
id: '6'
}
]
},
{
id: '7',
name: '佛山市',
children: [
{
name: '佛山1区',
id: '8'
},
{
name: '佛山2区',
id: '9'
}
]
}
]
},
{
name: "湖北省",
id: '2',
children: [
{
id: '10',
name: '武汉市',
children: [
{
name: '江汉区',
id: '11'
},
{
name: '汉口区',
id: '12'
}
]
}
]
}
];
console.log("试试递归", this.find(list, '4'));
},
find(list, id) {
console.log("123456")
if (!list || !id) {
return ''
}
let arr = [];
let findParent = (data, nodeId, parentId) => {
for (var i = 0, length = data.length; i < length; i++) {
let node = data[i];
if (node.id === nodeId.toString()) {
arr.unshift(data[i]);
if (nodeId.toString() === list[0].id) {
break
}
findParent(list, parentId);
break
} else {
if (node.children) {
findParent(node.children, nodeId, node.id);
}
continue
}
}
return arr;
}
return findParent(list, id);
},
}
}
</script>
运行在控制台看一下,如下图:
|