Danielle
Danielle

Reputation: 1496

Angular2. Checkif a Json Key has content

on the following Json, I receive different products to show on screen. Please notice "Medical250" has values, but "hospital", "life" and "dental" doesnt. This happens depending on the state I send to the API feed (and age).

{
    "success": "1",
    "quotekey": "1e2532897f24a46b98799665e43052423",
    "membership": [{
            "planid": "1",
            "membership": "Select Basic",
            "fee": "10.95"
        },
        {
            "planid": "2",
            "membership": "Select Silver",
            "fee": "19.95"
        },
        {
            "planid": "3",
            "membership": "Select Gold",
            "fee": "29.95"
        },
        {
            "planid": "4",
            "membership": "Select Platinum",
            "fee": "39.95"
        },
        {
            "planid": "5",
            "membership": "Select Diamond",
            "fee": "49.95"
        }
    ],
    "dental": [],
    "medical0": [],
    "medical250": [{
            "plannumber": "1",
            "single": "9.49",
            "couple": "18.97",
            "singlewithdependents": "21.82",
            "family": "26.56"
        },
        {
            "plannumber": "2",
            "single": "12.28",
            "couple": "24.55",
            "singlewithdependents": "28.23",
            "family": "34.37"
        },
        {
            "plannumber": "3",
            "single": "14.07",
            "couple": "28.14",
            "singlewithdependents": "32.36",
            "family": "39.40"
        },
        {
            "plannumber": "4",
            "single": "16.74",
            "couple": "33.48",
            "singlewithdependents": "38.50",
            "family": "46.87"
        }
    ],
    "hospital": [],
    "life": []
}

Im parsing that Json and getting the values as follows:

this.MedicalQuote = this.APIresult[0].medical250[0].single;

etc... but when I try to get this.APIresult[0].dental[0].single; which doesnt exist, my code crashes. Is there a way to identify if a key, like "dental" in this case, contains any value or if it just empty []? All keys have a value called "single", except for "membership" which will always contain values.

I am now doing try - catch (e) for each product but it doesnt look like a clean solution, I would like to do it the right way.

Thanks.

Upvotes: 1

Views: 264

Answers (2)

igor_c
igor_c

Reputation: 1250

You can add the ? sign after properties which can be empty and it'll return undefined.

const result = this.APIresult[0].dental[0]?.single

Then the result variable will be undefined and you can work with it as you need.

Upvotes: 2

David Gerschcovsky
David Gerschcovsky

Reputation: 121

Use an "if" statement to check if the property exists, for example:

if(thisSession.hasOwnProperty('dental')){
    //your code...
}

Upvotes: 3

Related Questions