Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

javascript: empty array value

I have the following loop which calls an api and pushes data to an array, the issue is that the API is returning empty values for certain attributes i.e "primaryTag": null and is breaking my code, how can I handle it to place a static value if any of the values are null?

for (var a in audience) {
        
      var aId = audience[a];
      var url = base+'?'+query+'&AudienceId='+aId
      var req = new HttpClientRequest(url);
      req.header["Content-Type"] = "application/json"
      req.method = "GET"
      req.execute();
      var resp = req.response;  
       
      if( resp.code != 200 )
      throw "HTTP request failed with " + resp.message
         
      var posts = JSON.parse(resp.body)
      logInfo(resp.code+' '+url);

      
        for (i = 0; i < 11; i++) {
          articlesList_json.push({
                "title":posts[i].title, 
                "pubDate":posts[i].publishedDate, 
                "link":posts[i].url, 
                "imageURL":posts[i].imageUrl, 
                "description": posts[i].description,
                "category": posts[i].category.name,
                "audience": posts[i].audience.name+'-'+posts[i].audience.id,
                "tag": posts[i].primaryTag.name,
                "episerverId":posts[i].episerverId,
            });
        } 
      
}//for loop end

enter image description here

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Have a look at optional chaining

"tag": posts[i].primaryTag?.name ?? "N/A"

Alternatively use a ternary:

"tag": posts[i].primaryTag ? posts[i].primaryTag.name : "N/A"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading