Search code examples
javascriptnode.jsecmascript-5

How to search for a key in an object's prototype?


I have an Object which has Objects inside it like this:

obj = {
foo:{x},
bar:{y},

}

i want to search for a key in the sub-objects prototype i.e bar in this context

i have tried this so far without success

for(x in obj){
    if(Object.keys(x.prototype).includes("key_to_be_searched")){
       console.log("true")
}
}

even logging x.prototype returns empty arrays

i am a newbie, so i would really appreciate in-depth explanation or resources where i can learn more about prototypes.


Solution

  • You can check recursively:

    const obj = {
      foo: { x: 'x' },
      bar: { y: 'y' },
    }
    
    const checkObjectProp = (o, p) => Object
      .keys(o)
      .some(k => k === p || (typeof o[k] === 'object' && checkObjectProp(o[k], p)))
    
    // Test
    const arr = ['foo', 'y', 'asdfasdf']
    arr.forEach(p => console.log(checkObjectProp(obj, p)))