遞迴列出巢狀物件鍵 JavaScript
假設我們有一個物件,其屬性值為其他物件,它嵌套了 2-3 層甚至更多。
這是一個示例物件:
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 } } }
我們的任務是編寫一個函式,該函式接受此物件和一個字串,在整個物件中搜索該字串作為鍵,並返回一個數組,其中包含與該字串匹配的所有鍵的值。
讓我們將該函式稱為 recursiveSearch(),鑑於巢狀,遞迴將是解決這種情況的最合適方法。
因此,此函式 recursiveSearch() 的完整程式碼將為:
示例
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'));
輸出
控制檯中的輸出將為:
[ 31, 22, 26 ]
在上述函式中,首先我們迭代主物件,並在遇到巢狀時遞迴迭代子物件搜尋所需的鍵,如果找到所需的鍵,我們立即將其值記錄在 results 陣列中,最後當我們完成迭代時,我們返回包含所需值的 results 陣列。
此函式的時間複雜度為 O(mn),其中 n 是主物件內子物件的個數,m 是巢狀的最深層級。
廣告