Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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:
- Base Case: When a matching key is found with a non-object value, it's added to results
- Recursive Case: When an object value is encountered, the function calls itself on that nested object
- 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.
