typescript 如何在TypeScript中检查对象是否具有属性并且属性值是否为真

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48635669/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:12:26  来源:igfitidea点击:

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

angulartypescript

提问by LearnToday

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

我想检查以下对象是否具有该属性forums以及该属性值是否为true.

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

I am using TypeScript Angular 5.

我正在使用 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?

是否有 Angular 方式或 TypeScript 方式?

回答by Vivek Doshi

Shortest way ,this will check both by default :

最短的方法,这将默认检查两个:

if(this.itemsmodel[item])

First it will try to fetch this.itemsmodelof itemif there is not then it will return undefinedand if it's found then it will return value,

首先它会尝试获取this.itemsmodelitem如果没有则返回undefined,如果找到则返回值,



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