Iterate till the end of the nested objects in javascript

I have a nested object like this :

let obj = {
_id: {},
person: {
    $search: {
        lname: true
    },
    _id: {},
    fname: {},
    something:{
        $search: {
            fname: true
        },
    }
},
code: {},
$search: {
    mname: true
},
vnvEmpName: {}
}

I have to retrieve all the keys inside the $search key, even if the object contains multiple occurences of $search it should return all the keys inside it which is :

lname 
fname
mname

I tried this :

function search(obj, id) {
var result = "";
// iterate the object using for..in

    for (var keys in obj) {
        // check if the object has any property by that name
        if (obj.hasOwnProperty(keys) && typeof obj[keys] === 'object') {
            // if the key is not undefined get it's value
            if (obj[keys][id] !== undefined) {
                result = (obj[keys][id])
            } else {
                // else again call the same function using the new obj value
                console.log("reahced")
                search(obj[keys], id)
            }
        }

    }
    return result;

}
console.log(search(obj, '$search'))

But I am getting only the key(lname) which is under the first instance of the $search. Please help me out to iterate it till the end.

13 thoughts on “Iterate till the end of the nested objects in javascript”

Leave a Comment