上午接到一个新业务,具体内容如下: 查询树形结构的数组对象,输入框输入一个值,模糊查找该值是否在树形数组结构中,如果在就返回当前区域内的所有值,反则,返回全部值;
分析业务
一听到是要在树形结构的数组对象中找对应的值,立马脑海出现“递归”二字,说干就干,接下来上代码 上代码前先说一下我也是在网上东拼西凑的哈,如有雷同、纯处巧合哈
#vue3 的写法
<script>
setup() {
const dataScource = reactive([
{
label: '奇葩名字',
children: [
{
label: '张三',
children: [
{
label: '张四',
children: [
{
label: '张五',
children: [
{
label: '小六'
}
]
}
]
}
]
},
{
label: '李四',
},
{
label: '王二',
children: [
{
label: '大王'
},
{
label: '小王'
}
]
}
]
}
]);
const data = reactive({})
const recursiveFn = function(ary, label) {
(function f(ary, label, data) {
for(let i = 0; i<ary.length; i++) {
const obj = ary[i];
if(obj['label'].indexOf(label) != -1) {
data = obj;
} else if(obj.hasOwnProperty('children')) {
f(obj['children'], label, data);
}
}
})(ary, label, data);
console.log(data['children'][0]['label'])
}
recursiveFn(dataScource, '张四')
return {
recursiveFn,
data
}
}
</script>
以上就是全部代码逻辑,希望对各位有所帮助,喜欢记得三联哦