Cho đối tượng lồng nhau 2-3 cấp. Mẫu:
const people = { Ram: { fullName: 'Ram Kumar', details: { age: 31, isEmployed: true } }, Sourav: { fullName: 'Sourav Singh', details: { age: 22, isEmployed: false } }, Jay: { fullName: 'Jay Grewal', details: { age: 26, isEmployed: true } } }Viết hàm nhận đối tượng và chuỗi, tìm toàn bộ đối tượng các key khớp chuỗi, trả mảng giá trị.
Hàm recursiveSearch() dùng đệ quy:
Ví dụ
const people = { Ram: { fullName: 'Ram Kumar', details: { age: 31, isEmployed: true } }, Sourav: { fullName: 'Sourav Singh', details: { age: 22, isEmployed: false } }, Jay: { fullName: 'Jay Grewal', details: { age: 26, isEmployed: true } } } const recursiveSearch = (obj, searchKey, results = []) => { const r = results; Object.keys(obj).forEach(key => { const value = obj[key]; if(key === searchKey && typeof value !== 'object'){ r.push(value); }else if(typeof value === 'object'){ recursiveSearch(value, searchKey, r); } }); return r; }; console.log(recursiveSearch(people, 'age'));Kết quả
Đầu ra console:
[ 31, 22, 26 ]
Duyệt object, gặp lồng thì đệ quy, tìm key khớp thì push value vào mảng kết quả.
Độ phức tạp O(mn) với m số object con, n độ sâu lồng tối đa.