0

I've the following JSON result. I have to display onto a web page three dates with types: onsaleDate, focDate, unlimitedDate. These fields are "values" to the keys "date". I'm currently accessing the dates by using dates[0].date, dates[1].date and dates[2].date. The problem, however, is that some of the other dates results do not necessarily have all of the three items with types onsaleDate, focDate, unlimitedDate. How can I check that these three date types exist before I assign them to a variable for display onto the page? Do I need a conditional loop? Can I use hasOwnProperty for nested items?

"results": [
   "dates": [
       {
         "type": "onsaleDate",
         "date": "2011-10-12T00:00:00-0400"
       },
       {
         "type": "focDate",
         "date": "2011-09-12T00:00:00-0400"
       },
       {
         "type": "unlimitedDate",
         "date": "2012-12-18T00:00:00-0500"
       },
       {
         "type": "digitalPurchaseDate",
         "date": "2012-05-01T00:00:00-0400"
       }
     ]
Kuan E.
  • 373
  • 1
  • 3
  • 15

2 Answers2

0

I would deal with issue by modifying the datatype of the results:

results = JSON.parse(results);
var dates = {};
results.dates.forEach(obj => dates[obj.type] = obj.date);
results.dates = dates;

//now you can access them by
if(results.dates.onsaleDate){
  // display on sale date....
}
mido
  • 24,198
  • 15
  • 92
  • 117
0

To find if a particular type exists in an object in an array, you can use find:

results.dates.find(obj => obj.type === "onsaleDate")

You can generalize this by writing a little function taking a particular property name, and returning a function suitable for passing to find:

function hasType(type) { 
  return function(o) { return o.type === type; };
}

Now you check for the presence of onsaleDate with

results.dates.find(hasType("onsaleDate"))

Or check for all three with

results.dates.find(hasType("onsaleDate")) && results.find(hasType("...

or, if you prefer

["onsaleDate", "focDate", "unlimitedDate"] . 
  every(type => results.dates.find(hasType(type)))