0

I am trying to check for an object property, but I can't understand why the second option returns false. Could anyone explain? Also, are there any other better ways to check properties?

let question = {
    category: 'test'
}

console.log(question.hasOwnProperty('category')); // true

this wont work

let question = {
    category: 'test'
}

console.log(question.hasOwnProperty(question.category)); // false
Dave
  • 1
  • 1
  • 9
  • 38
  • 4
    It returns false because you don't have a property with the name `test`. *(not my downvote)* Your first code block shows correctly asking if the object has a `category` property. Your second asks if it has a property with a name that you're getting from `question.category`, which is the string `test`. – T.J. Crowder May 10 '22 at 17:33
  • 1
    Does this answer your question? [How do I check if an object has a specific property in JavaScript?](https://stackoverflow.com/questions/135448/how-do-i-check-if-an-object-has-a-specific-property-in-javascript) – Konrad May 10 '22 at 17:33
  • if ('category' in question) { .... – Hugeen May 10 '22 at 17:37
  • This is just a typo, it should be taken down. – KoderM May 10 '22 at 17:39

3 Answers3

0

const obj = {
    foo: 'bar',
};

// Check if an object has a certain key somewhere
console.log('foo' in obj);
console.log(!!obj['foo']);
console.log(obj.hasOwnProperty('foo'))

// Check if an object has a certain value somewhere
console.log(Object.values(obj).includes('bar'));
mstephen19
  • 1,733
  • 1
  • 5
  • 20
-1

In this line:

question.hasOwnProperty(question.category)

The part question.category returns 'test' and you haven't 'test' like property, just leave it like that:

question.hasOwnProperty(category)

lsanchezo
  • 134
  • 8
-1

You can also check property using:

'category' in question