查找树形结构的某对象
今天遇到这个需求:有一个树形结构,查找 id=5 的对象,并输出
感觉很简单,一个小时没搞出来~
记录下
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>根据id从树形图中查找对象</title> </head> <body> <script> // 树形结构 var originData = [ { id: 1, name: 'name1', children: [ { id: 11, name: 'name11', children: [ { id: 111, name: 'name111', children: [ { id: 1111, name: 'name1111' } ] }, { id: 112, name: 'name112' } ] } ] }, { id: 2, name: 'name2', children: [ { id: 21, name: 'name21', children: [ { id: 211, name: 'name211' }, { id: 212, name: 'name212', children: [ { id: 2121, name: 'name2121' } ] } ] } ] }, { id: 3, name: 'name3', children: [ { id: 31, name: 'name31', children: [ { id: 311, name: 'name311', children: [ { id: 3111, name: 'name3111', children: [ { id: 31111, name: 'name31111' } ] } ] } ] } ] } ]; function searchiInTree(data, id) { let result = null; if (!data) { return; } for (let key in data) { if (result !== null) { break; } if (data[key].id == id) { result = data[key]; break; } else if (data[key].children && data[key].children.length > 0) { result = searchiInTree(data[key].children, id); } } return result; } let obj = searchiInTree(originData, 11); // 返回根据 id 查找到的数据对象 console.log(obj); </script> </body> </html>