前提条件:数组对象中的id唯一
1 const tree = [ 2 {id: 1}, 3 {id:2, 4 children:[ 5 {id: 3, 6 children:[ 7 {id: 4, 8 children: [ 9 {id: 5} 10 ] 11 } 12 ] 13 } 14 ] 15 } 16 ]
- 面试题-通过id,在上述数据中找出id所在的对象
1 function getItem(data, searchId){ 2 let result; 3 if(Array.isArray(data)){ 4 for(let item of data) { 5 const {id, children} = item; 6 if (searchId === id) { 7 result = item; 8 break; 9 } 10 if(Array.isArray(children)){ 11 result = getItem(children, searchId) 12 } 13 } 14 } else { 15 console.log('没有找到'); 16 return null; 17 } 18 return result; 19 }
- 面试题-通过id,获取父节点id
1 function getParentId(data, searchId, parentId) { 2 let result; 3 if(Array.isArray(data)){ 4 for (let item of data) { 5 const {id, children} = item; 6 if (id === searchId) { 7 result = parentId; 8 break; 9 } 10 if(Array.isArray(children)){ 11 result = getParentId(children, searchId, id); 12 } 13 } 14 } else { 15 return 'null' 16 } 17 18 return result; 19 }
- 面试题-通过id,获取所有的上级节点id
1 function getAllParentIds(data, searchId, parentIds = []) { 2 let result; 3 if(Array.isArray(data)){ 4 for (let item of data) { 5 const {id, children} = item; 6 if (id === searchId) { 7 result = parentIds; 8 break; 9 } 10 if(Array.isArray(children)){ 11 result = getAllParentIds(children, searchId, parentIds.concat(id)); 12 } 13 } 14 } else { 15 return 'null' 16 } 17 18 return result; 19 }