Check if a object is defined, best practice.

前端 未结 4 775
滥情空心
滥情空心 2020-12-15 17:04

I have the following JSON response from a ajax-request.

var json = {
    \"response\": {
        \"freeOfChargeProduct\": {  
        \"description\": \"Prod         


        
4条回答
  •  既然无缘
    2020-12-15 18:03

    Use the guard pattern:

    if (json.response && json.response.freeOfChargeProduct && json.response.freeOfChargeProduct.details) {
        // you can safely access the price
    }  
    

    This is how the guard pattern works.

    if (a && a.b && a.b.c) { ... } else { ... }
    

    The first check is "Does the property a exist?". If not, the else-branch gets executed. If yes, then the next check occurs, which is "Does object a contain the property b?". If no, the else-branch executes. If yes, the final check occurs: "Does the object a.b contain the property c?". If no, the else-branch executes. If yes (and only then), the if-branch executes.

    Update: Why is it called "guard pattern"?

    var value = a && b;  
    

    In this example, the member b (the right operand) is guarded by the && operator. Only if the member a (the left operand) is truthy ("worthy"), only then the member b is returned. If, however, the member a is falsy ("not worthy"), then it itself is returned.

    BTW, members are falsy if they return these values: null, undefined, 0, "", false, NaN. Members are truthy in all other cases.

提交回复
热议问题