1

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.

  • Why do you need to check its prototypes, it's just another object, using `Object.keys(x)`, this will return `['x']` – deko_39 Apr 07 '22 at 09:42
  • Read more about __proto__ and prototype of `function`, not mere `object` in JS here: https://stackoverflow.com/questions/9959727/proto-vs-prototype-in-javascript – deko_39 Apr 07 '22 at 09:52

2 Answers2

1

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)))
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46
0
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

  • Sorry, i did not convey the information correctly. the Object has been defined by an external library. i just need to search inside each sub objects prototype for a specific key – Icecreamdroid Apr 07 '22 at 08:27