深度搜索 JSON 物件 JavaScript


假設我們有以下巢狀的 JSON 物件 −

const obj = {
   id: 1,
   title: 'hello world',
   child: {
      id: null,
      title: 'foobar',
      child: {
         id: null,
         title: 'i should be in results array '
      }
   },
   foo: {
      id: null,
      title: 'i should be in results array too!' },
      deep: [
      {
         id: null,
         value: 'yo'
      }, {
         id: null,
         value: 'yo2'
      }
   ]
};

我們需要編寫一個 JavaScript 函式,該函式接收一個這樣的物件作為第一個引數、一個鍵字串作為第二個引數以及一個值字串作為第三個引數。然後,該函式應在 JSON 物件中檢查給定的鍵值對。

如果有任何物件,則函式應返回所有此類物件的陣列。

我們將使用以下方法來解決此問題 −

  • 如果搜尋的專案為假或不是物件,那麼我們返回
  • 如果給定的鍵和值匹配,那麼我們向結果集新增實際物件,
  • 我們獲得鍵並迭代遍歷屬性並再次呼叫函式。

最後,我們返回包含已收集到的物件的陣列。

示例

const obj = {
   id: 1,
   title: 'hello world',
   child: {
      id: null,
      title: 'foobar',
      child: {
         id: null,
         title: 'i should be in results array '
      }
   },
   foo: {
      id: null,
      title: 'i should be in results array too!' },
      deep: [
      {
         id: null, value: 'yo'
      }, {
         id: null, value: 'yo2'
      }
   ]
};
const findObject = (obj = {}, key, value) => {
   const result = [];
   const recursiveSearch = (obj = {}) => {
      if (!obj || typeof obj !== 'object') { return;
   };
   if (obj[key] === value){
      result.push(obj);
   };
   Object.keys(obj).forEach(function (k) {
      recursiveSearch(obj[k]);
   });
} recursiveSearch(obj);
return result;
} console.log(findObject(obj, 'id', null));

輸出

[
   {
      id: null,
      title: 'foobar',
      child: {
         id: null, title: 'i should be in results array '
      }
   },
   {
         id: null, title: 'i should be in results array '
   }, {
         id: null, title: 'i should be in results array too!'
      }, {
      id: null, value: 'yo'
      }, { id: null, value: 'yo2'
   }
]

更新時間: 2020 年 11 月 21 日

6K+ 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.