jeremy
jeremy

Reputation: 185

Check if the variable/key exist

I have a value customer with different condition :

My json structure is like this for the first and second condition :

json:
  fields:
    customer [1]:
      0 {3}:
        self: aaa
        value: yes
        id: 111

And my json structure is like this for the last condition :

json:
  fields:
    customer:null

I'm trying to do something like this :

var customer = json.fields.customer[0].value ;  
var score3 = 0;
    if(typeof customer == 'string'){          
        if(customer === "Yes"){
            score3 = +10;
        }
        else if(customer === "No"){
            score3 = +5;
        }
    }
    else{
        score3 = 0;
    } 

But I have a problem who says: "Cannot read property '0'"

Thanks for you help

Upvotes: 0

Views: 76

Answers (1)

Hien Nguyen
Hien Nguyen

Reputation: 18975

You did not check null for customer

     var customer = 
json.fields.customer != null && json.fields.customer.length > 0 ? json.fields.customer[0].value : null;  

Upvotes: 1

Related Questions