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?
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';
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With