LearnToday
LearnToday

Reputation: 2902

How to check if object has property and property value is true in TypeScript

I want to check if the following object has the property forums and if that property value is true.

{forums: true, pages: true, photos: true, videos: true}

I am using TypeScript Angular 5.

I do this for now and works fine.

let item = 'forums';
if ( this.itemsmodel.hasOwnProperty(item) ) {
   //Which is true. 
   if (this.itemsmodel[item]) {
          item = item;
   } else {
          item = 'pages';
   }
}

Is there an Angular way or TypeScript way for this?

Upvotes: 8

Views: 32345

Answers (1)

Vivek Doshi
Vivek Doshi

Reputation: 58523

Shortest way ,this will check both by default :

if(this.itemsmodel[item])

First it will try to fetch this.itemsmodel of item if there is not then it will return undefined and if it's found then it will return value,


Same but long way of doing :

if(this.itemsmodel[item] && this.itemsmodel[item] === true)

Here first will check if key exists , second will check for the value


As result you can convert your code to something like this :

let item = 'forums';
if (this.itemsmodel[item]) {
        item = item;
} else {
        item = 'pages';
}

Upvotes: 7

Related Questions