Cho object lồng nhiều cấp. Viết hàm đệ quy tìm tất cả giá trị của key cho trước (ví dụ 'age') trong toàn bộ object.
Mã thực hiện
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ả
[ 31, 22, 26 ]
Độ phức tạp O(m*n) với m số object con, n độ sâu lồng nhau.