Deep Search JSON Object JavaScript


Suppose we have the following nested JSON object −

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'
      }
   ]
};

We are required to write a JavaScript function that takes in one such object as the first argument, a key string as the second and a value string as the third argument. The function should then check for the given key value pair in the JSON object.

If there exists any object then the function should return an array of all such objects.

We will use the following approach to solve this problem −

  • if the searched item is false or if it’s not an object, then we return
  • if given key and value match, then we add the actual object to the result set,
  • we get the keys and iterate over the properties and call the function again.

At last, we return the array with the collected objects.

Example

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));

Output

[
   {
      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'
   }
]

Updated on: 21-Nov-2020

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements