dipgirl
dipgirl

Reputation: 690

How to check the element in object Ionic 4

I am using Ionic 4. I post the data to my API then I get the return result like this:

{
    "responses": [
        {
            "Detection": {
                "Images": [
                    {"url":"https:URL"}, 
                ],
                "Ages": [
                    {"age":"33"}, 
                ],
                "Labels":[
                    {"label":"game"}
                ]
            }
        }
    ]
}

But sometimes the 'Ages" is not returned. So, my question is how can I check the element in return object from API? For example, I want to check is the response has return "Ages[]" or not? How can I write the condition?

Upvotes: 2

Views: 228

Answers (2)

rtpHarry
rtpHarry

Reputation: 13125

If your project is running the recently released TypeScript 3.7 then you can use the new Optional Chaining feature.

It lets you use ?. to chain it together, and if one of the elements doesn't exist then instead of an error it just returns undefined.

This would let you write something like:

let firstAge = this.data.responses[0].Detection?.Ages?.[0].age;

Which would result in either 33 in your example json, or undefined if it didn't exist.

Upvotes: 1

Chanaka Weerasinghe
Chanaka Weerasinghe

Reputation: 5742

you can access like this;

here is working Example

data={
    "responses": [
        {
            "Detection": {
                "Images": [
                    {"url":"https:URL"}, 
                ],
                "Ages": [
                    {"age":"33"}, 
                ],
                "Labels":[
                    {"label":"game"}
                ]
            }
        }
    ]
}

this.data.responses[0].Detection.Ages[0].age
console.log("Age :",his.data.responses[0].Detection.Ages[0].age);

//check ages presents

let ages=this.data.responses[0].Detection.Ages

 if(ages.length)
 {
   console.log("Age object present :",ages.length);
 }

Upvotes: 1

Related Questions