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

前端 未结 4 1159
萌比男神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: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..
    }
    

提交回复
热议问题