Recursively list nested object keys JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

Let’s say, we have an object with other objects being its property value, it is nested to 2-3 levels or even more.

Here is the sample object −

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
      }
   }
}

Our job is to write a function that accepts this object and a string, searches the whole object for that string as key and returns an array that contains value of all the keys that matched with the string

Let’s call the function recursiveSearch(), recursion would be the most appropriate way of tackling this situation, given the nesting.

So, the full code for this function recursiveSearch() will be −

Example

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

Output

The output in the console will be −

[ 31, 22, 26 ]

In the above function, first of all we iterate over the main object and whenever we encounter a nesting we recursively iterate over the sub object search for the desired key, if we find the desired key, we immediately record its value in the results array and at the last when we finish iterating, we return the results array that contains the desired values.

The time complexity of this function is O(mn) where is the number of child objects inside the main object and m is the deepest level of nesting.

raja
Published on 19-Aug-2020 10:27:21
Advertisements