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

前端 未结 4 1052
萌比男神i
萌比男神i 2020-12-31 04:28

Suppose I have the next javascript object:

var errors = {
    error_1: \"Error 1 description\",
    error_2: \"Error 2 description\",
    error_3: \"\",
             


        
相关标签:
4条回答
  • 2020-12-31 04:50

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

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

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

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

    Result:

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

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

    0 讨论(0)
  • 2020-12-31 04:50

    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
    
    0 讨论(0)
  • 2020-12-31 04:52

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

    if (Object.keys(object_name).length > 0) {
    
      // Your code
    
    }
    
    0 讨论(0)
  • 2020-12-31 04:55

    Here is a another good answer I found and 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..
    }
    
    0 讨论(0)
提交回复
热议问题