js递归找出id所在的对象
根据value,找出value所在对象
const data = [{label: '北京',
value: '110000',
children: [{
label: '北京市',
value: '110100',
children: [{
label: '东城区',
value: '110101'
}, {
label: '西城区',
value: '110102'
}]
}]
}]
回答
https://www.npmjs.com/package/tree-tool
https://segmentfault.com/search?type=question&q=递归
好了,闲话不多说,我找到了历史回答,然后我又来混每日一答来了。
function findId(Arr, ID) { var _result = null;
for (let i = 0; i < Arr.length; i++) {
//console.log(Arr[i], Arr[i].id == ID)
if (Arr[i].value == ID) return Arr[i];
if (Arr[i].children) _result = findId(Arr[i].children, ID)
if (_result != null) return _result;
}
return _result
}
data = [{
label: '北京',
value: '110000',
children: [{
label: '北京市',
value: '110100',
children: [{
label: '东城区',
value: '110101'
}, {
label: '西城区',
value: '110102'
}]
}]
}]
findId(data, '110101')
const data = [{ label: '北京',
value: '110100',
children: [{
label: '北京市',
value: '110100',
children: [{
label: '东城区',
value: '110101'
}, {
label: '西城区',
value: '110102'
}]
}]
}]
var foo = (data,id) => {
for(let i=0;i<data.length;i++){
var item = data[i];
if(item.value == id){
return {...item}
}
if(item.children && item.children.length){
return foo(item.children,id)
}
}
}
console.log(foo(data,110101))
以上是 js递归找出id所在的对象 的全部内容, 来源链接: utcz.com/a/68397.html