使用遞迴在 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'));

在此函式中,首先我們遍歷主物件,每當遇到巢狀時,我們就會遞迴遍歷子物件以搜尋所需的鍵,如果我們找到所需的鍵,我們立即將它的值記錄在 results 陣列中,最後當我們完成遍歷時,我們返回包含所需值的 results 陣列。

此函式的時間複雜度為 O(mn),其中 n 是主物件內部子物件的個數,m 是巢狀的最深層級。

此程式碼在控制檯中的輸出將為:

[ 31, 22, 26 ]

更新時間: 2020年10月9日

1K+ 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.