Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 755
LearnToday Avatar asked Feb 06 '18 04:02

LearnToday


1 Answers

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';
}
like image 56
Vivek Doshi Avatar answered Sep 21 '22 04:09

Vivek Doshi