如何检查JavaScript对象中是否存在键?

Consider the following object,

考虑以下对象,

const cookie= {
	flavour: 'Chocolate', 
	size: 'medium', 
	company: 'Parle'
}

console.log(cookie);

Output

输出量

{flavour: "Chocolate", size: "medium", company: "Parle"}

We have a simple cookie object having three properties; flavour, size and company that makes the cookies. Now let's say we want to know the color of the cookie,

我们有一个简单的cookie对象,它具有三个属性: 曲奇的 风味 , 大小和公司 。 现在假设我们想知道Cookie的颜色,

console.log(cookie.color);

Output

输出量

undefined

How were we so sure that the cookie had a color? Maybe we weren't given this information in the first place. So how do we first check if the cookie had this property or in general any object has a property?

我们如何确定cookie的颜色? 也许我们一开始没有得到这些信息。 那么,我们如何首先检查Cookie是否具有此属性,或者通常任何对象都具有属性?

1)使用in运算符 (1) Using in operator)

The first method is using the in operator. The in operator checks for a property in an object and returns a boolean value.

第一种方法是使用in运算符in运算符检查对象中的属性并返回布尔值。

console.log('color' in cookie);
console.log('size' in cookie);

Output

输出量

false
true

Since color is a property that does not exist in our cookie, we get a false and for size, we get true because our cookie had a size property.

由于color是cookie中不存在的属性,因此我们得到false,而对于size ,则得到true,因为cookie具有size属性。

2)hasOwnProperty()方法 (2) hasOwnProperty() method)

There is another way through which we can do this, using the hasOwnProperty() method. It also returns us a boolean value indicating if the object had that property or not.

我们还有另一种方法可以使用hasOwnProperty()方法 。 它还返回一个布尔值,指示对象是否具有该属性。

const bunny={
	name: 'Bugs Bunny',
	teeth: 2,
	color: 'white',
	isEndangered: false
}
console.log(bunny);

Output

输出量

{name: "Bugs Bunny", teeth: 2, color: "white", isEndangered: false}

Using the hasOwnProperty(), we'll check if our bunny object has a property habitat.

使用hasOwnProperty() ,我们将检查我们的兔子对象是否具有属性栖地 。

console.log(bunny.hasOwnProperty('habitat'));

Output

输出量

false

Let's check if it has a property named color,

让我们检查一下它是否具有名为color的属性。

console.log(bunny.hasOwnProperty('color'));

Output

输出量

true

Now that we know how to check if a property exists in an object, let's see where it can be used. Imagine you're a frontend developer and you have to manage a website where some data about a user comes from the backend, an API or a server which you have to display for a particular user's account. Now you have various fields however you don't know what data user filled. Only that data about the user was stored which the user entered. So let's say the user entered the following information and you got back a json object which you converted to a normal JS object that looks something like this,

现在,我们知道如何检查对象中是否存在属性,让我们看看可以在哪里使用它。 假设您是一名前端开发人员,并且您必须管理一个网站,其中有关用户的某些数据来自后端,必须为特定用户帐户显示的API或服务器。 现在您有多个字段,但是您不知道用户填写了什么数据。 仅存储用户输入的有关用户的数据。 假设用户输入了以下信息,然后您获得了一个json对象,该对象已转换为看起来像这样的普通JS对象,

const user377_19={
	name: 'Harry',
	age: 22,
	email: '[email protected]',
	address: '43/5 H block new coastal colony',
	userID: '351817bjhh1937t13b7f379371fjfuifh3y1397'
}

Now if you output a property that doesn't exist, it will be a bad user interface design. So before outputting, we'll check if a particular property exists.

现在,如果您输出一个不存在的属性,那将是错误的用户界面设计。 因此,在输出之前,我们将检查是否存在特定属性。

function checkIfexists(object, prop) {
    if (object.hasOwnProperty(prop))
        return `${prop} Exists, proceed to display`;
    else
        return `${prop} info does not exist`;
}

Let's call this function to see if it has the properties we need.

让我们调用此函数以查看它是否具有所需的属性。

const props=['name','age','email','address','phoneno']
props.forEach(prop=>console.log(checkIfexists(user377_19,prop)));

Output

输出量

name Exists, proceed to display
age Exists, proceed to display
email Exists, proceed to display
address Exists, proceed to display
phoneno info does not exist

Hence using the "in operator" or the hasOwnProperty() method we can check if an object has a key inside it with the given name and use it to conditionally output content.

因此,使用“ in运算符”hasOwnProperty()方法,我们可以检查对象内部是否具有具有给定名称的键,并使用该键有条件地输出内容。

翻译自: https://www.includehelp.com/code-snippets/how-to-check-if-a-key-exists-in-a-javascript-object.aspx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值