Fetching object keys using recursion in JavaScript

When working with nested objects in JavaScript, you often need to search for specific keys at any level of nesting. Recursion provides an elegant solution for traversing these complex data structures.

The Problem

Consider a nested object structure where we need to find all values for a specific key across all levels:

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 goal is to create a function that searches the entire object for a specific key and returns an array containing all matching values.

Recursive Solution

The recursiveSearch() function uses recursion to traverse nested objects and collect matching key values:

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'));
console.log(recursiveSearch(people, 'fullName'));
console.log(recursiveSearch(people, 'isEmployed'));
[ 31, 22, 26 ]
[ 'Ram Kumar', 'Sourav Singh', 'Jay Grewal' ]
[ true, false, true ]

How It Works

The function operates through these steps:

  1. Base Case: When a matching key is found with a non-object value, it's added to results
  2. Recursive Case: When an object value is encountered, the function calls itself on that nested object
  3. Accumulation: The results array is passed by reference, collecting matches from all levels

Enhanced Version with Null Handling

const recursiveSearchEnhanced = (obj, searchKey, results = []) => {
    if (obj === null || typeof obj !== 'object') {
        return results;
    }
    
    Object.keys(obj).forEach(key => {
        const value = obj[key];
        if (key === searchKey && typeof value !== 'object') {
            results.push(value);
        } else if (value !== null && typeof value === 'object') {
            recursiveSearchEnhanced(value, searchKey, results);
        }
    });
    
    return results;
};

// Test with data containing null values
const testData = {
    user1: { name: 'Alice', profile: null },
    user2: { name: 'Bob', profile: { age: 25 } }
};

console.log(recursiveSearchEnhanced(testData, 'name'));
console.log(recursiveSearchEnhanced(testData, 'age'));
[ 'Alice', 'Bob' ]
[ 25 ]

Time Complexity

The time complexity is O(n × d), where:

  • n = total number of properties in all objects
  • d = maximum depth of nesting

Conclusion

Recursive search provides an efficient way to traverse nested objects and collect values by key. The enhanced version with null checking makes it more robust for real-world data structures.

Updated on: 2026-03-15T23:19:00+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements