Javascript 在Javascript中,如何确定对象属性是否存在且不为空?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28552589/
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-08-23 01:58:46  来源:igfitidea点击:

In Javascript, How to determine if an object property exists and is not empty?

javascript

提问by Amr

Suppose I have the next javascript object:

假设我有下一个 javascript 对象:

var errors = {
    error_1: "Error 1 description",
    error_2: "Error 2 description",
    error_3: "",
    error_4: "Error 4 description"
};

How can I determine if the property error_1exists in the errorsobject and is not empty as well?

如何确定该属性是否error_1存在于errors对象中并且也不为空?

回答by AhmadAssaf

if (errors.hasOwnProperty('error_1') && errors['error_1'] )

if (errors.hasOwnProperty('error_1') && errors['error_1'] )

The method hasOwnPropertycan be used to determine whether an object has the specified property as a direct property of that object.

该方法hasOwnProperty可用于确定对象是否具有作为该对象的直接属性的指定属性。

The errors[key]where keyis a string value checks if the value exists and is not null

errors[key]这里key是一个字符串值,将检查值存在,并且不为空

to Check if its not empty where it is a string then typeof errors['error_1'] === 'string' && errors['error_1'].lengthwhere you are checking for the length of a string

检查它是否不是空的,它是一个字符串,然后typeof errors['error_1'] === 'string' && errors['error_1'].length你检查字符串的长度

Result:

结果:

if (errors.hasOwnProperty('error_1') && typeof errors['error_1'] === 'string' && errors['error_1'].length)

if (errors.hasOwnProperty('error_1') && typeof errors['error_1'] === 'string' && errors['error_1'].length)

Now, if you are using a library like underscoreyou can use a bunch of utility classes like _.isEmpty_.has(obj,key)and _.isString()

现在,如果您使用像下划线这样的库,您可以使用一堆实用程序类,例如_.isEmpty_.has(obj,key)_.isString()

回答by Phil

To precisely answer your question (exists and not empty), and assuming you're not referring to empty arrays, you could use

要准确回答您的问题(存在且不为空),并假设您不是指空数组,您可以使用

typeof errors.error_1 === 'string' && errors.error_1.length

回答by Amr

Here is a another good answer I foundand wanted to share (after modification to fit my needs):

这是我找到并想分享的另一个很好的答案(经过修改以满足我的需要):

if ("property_name" in object_name && object_name.property_name !== undefined){
   // code..
}

So if I wanted to apply this on my example, it will look like:

因此,如果我想将其应用到我的示例中,它将如下所示:

if ("error_1" in errors && errors.error_1 !== undefined){
   // code..
}

回答by Armen Nersisyan

In order to check whether the object is empty or not use this code.

为了检查对象是否为空,请使用此代码。

if (Object.keys(object_name).length > 0) {

  // Your code

}