# Fetching object keys using recursion in JavaScript

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 −

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

In this 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.

The output in the console for this code will be −

[ 31, 22, 26 ]