js递归查询之根据id查询当前对象
需求:递归查询数组中id对应的数据
- Json数据格式:
1 let cityArr = [ 2 { 3 id: 1000, 4 name: '四川省', 5 children: [ 6 { 7 id: 1100, 8 name: '成都市', 9 children: [ 10 { id: 1101, name: '新都区' }, 11 { id: 1102, name: '高新区' } 12 ] 13 }, 14 { 15 id: 1200, 16 name: '绵阳', 17 children: [ 18 { id: 1201, name: '江油'}, 19 { id: 1202, name: '梓潼县'} 20 ] 21 } 22 ] 23 }, { 24 id: 2000, 25 name: '上海', 26 children: [ 27 { 28 id: 2100, 29 name: '市辖区', 30 children: [ 31 { id: 2101, name: '浦东新区'}, 32 { id: 2102, name: '闵行区'}, 33 ] 34 } 35 ] 36 } 37 ];
- 直接上代码:
1 export function getObjById(data, id) { 2 const isA = Array.isArray(data); 3 if (!isA) return; 4 for (let i = 0, len = data.length; i < len; i++ ) { 5 let item = data[i]; 6 if(item.id === id) { 7 return item; 8 } else { 9 if (item.children && item.children.length > 0) { 10 let obj = getObjById(item.children, id); 11 if(obj) return obj; 12 } 13 } 14 } 15 }
执行:getObjById(cityArr, 1101)
运行结果:
鉴定完毕,欢迎友友们一起交流学习!!
本文来自博客园,作者:红石榴21,转载请注明原文链接:https://www.cnblogs.com/liushihong21/p/17531715.html