Home > Software engineering >  Test if object contains property
Test if object contains property

Time:05-11

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

CodePudding user response:

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'));

CodePudding user response:

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)

CodePudding user response:

You can also check property using:

'category' in question
  • Related