Home > Software design >  How to search for a key in an object's prototype?
How to search for a key in an object's prototype?

Time:04-07

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.

CodePudding user response:

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

}

this is not how you declare anything inside prototype, the properties exists directly inside object not inside its prototype

instead of x.prototype just do x

CodePudding user response:

You can check recursively:

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

const checkObjectProp = (obj, prop) => Object
  .keys(obj)
  .some((k) => typeof obj[k] === 'object' 
    ? checkObjectProp(obj[k], prop) 
    : k === prop)

const result = checkObjectProp(obj, 'y')

console.log(result)

  • Related