search for a particular key in a nested object in nodejs

I have a nested object which looks like this :

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

}

I have to search for a $search keyword in this and get the key which is inside it that is fname in this case, it can contain multiple keys as well and I have to retrieve all of it.

I tried something like this :

function findById(obj, id) {                             

var result;
for (var p in obj) {
    if (obj.id === id) {
        return obj;
    } else {
        if (typeof obj[p] === 'object') {
            result = findById(obj[p], id);
            if (result) {
                return result;
            }
        }
    }
}
return result;

}

If the object is in this way :

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

}
I want to retrieve all the attributes inside the $search of every block.

but I don’t know how to get the keys inside a particular key as I am so new to the javascript.

25 thoughts on “search for a particular key in a nested object in nodejs”

Leave a Comment