前提條件:陣列物件中的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 }