Determine the presence of a JSON Value/Array in a web application using JavaScript and visualize the information in a dynamic

Utilizing the Ticketmaster API has provided me with a sample dataset from their platform,

Data 1 - Including information on "presales."

"sales": {
                "public": {
                    "startDateTime": "2019-11-22T17:00:00Z",
                    "startTBD": false,
                    "startTBA": false,
                    "endDateTime": "2021-09-25T23:00:00Z"
                },
                "presales": [
                    {
                        "startDateTime": "2019-11-18T16:37:00Z",
                        "endDateTime": "2019-11-22T04:00:00Z",
                        "name": "Verified Fan Presale"
                    },
                    // Other presale data entries...
                ]
            }

Data 2 - Without any records of "presales."

"sales": {
                "public"': {
                    "startDateTime": "2020-03-06T15:00:00Z",
                    "startTBD": false,
                    "startTBA": false,
                    "endDateTime": "2021-11-01T00:00:00Z"
                }
            }

I have multiple datasets, some containing presale details and others not. I'm iterating through all available data retrieved from the API.

Below is my source code, where I encounter an issue with json.has("presales"), causing an error.

// JavaScript function to retrieve event data
function showSearch(){
    var kword = document.getElementById("searchTxt").value;
    var inputCountry = document.getElementById("inputCountry").value;
    var startdateid = new Date(document.getElementById("startdateid").value);
    var enddateid = new Date(document.getElementById("enddateid").value);
  
    // Check if dates are valid
    if ( isNaN( startdateid.getTime() ) ) { 
        startdateid = "invalid";
    }
    if ( isNaN( enddateid.getTime() ) ) { 
        enddateid = "invalid";
    }

    // AJAX call to Ticketmaster API
    $.ajax({
        type:"GET",
        url:"https://app.ticketmaster.com/discovery/v2/events.json?keyword=" + kword + "&countryCode="+ inputCountry +"&size=200&apikey=Q8G0vn5ycUgMPGsnCGqLe1ZCP6GyY1uR",
        async:true,
        dataType: "json",
        success: function(json) {
                    console.log(json);
                    var e = document.getElementById("eventsfound");
                    e.innerHTML = json.page.totalElements + " events found.";
                    showEvents(json,startdateid,enddateid); // Display events in table
                },
        error: function(xhr, status, err) {
                }
    });
}

// Function to display events in DataTable
function showEvents(json,startdateid,enddateid) {
    var table = $('#example2').DataTable();
    var presaleStartCheck;
    var presaleEndCheck;
    var presaleNameCheck;
    table.clear();
    
    for(var i=0; i<json.page.size; i++) {
        var eDate = new Date(json._embedded.events[i].dates.start.localDate);
        var counter = i + 1;

        if((startdateid=="invalid") && (enddateid=="invalid")){
            if(json.sales.presales){ // Issue arises here, checking if presales exist
                presaleStartCheck = json._embedded.events[i].sales.presales[i].startDateTime;
                presaleEndCheck = json._embedded.events[i].sales.presales[i].endDateTime;
                presaleNameCheck = json._embedded.events[i].sales.presales[i].name;
               } else{
                presaleStartCheck = "Not applicable";
                presaleEndCheck = "Not applicable";
                presaleNameCheck = "Not applicable";
               }
            
            // Populate table with event details
            table.row.add( [
                counter,
                json._embedded.events[i].name,
                json._embedded.events[i].dates.start.localDate,
                json._embedded.events[i].dates.start.localTime,
                json._embedded.events[i].url,
                presaleStartCheck,
                presaleEndCheck,
                presaleNameCheck,
            ] ).draw();
        }
    }
}

showSearch(); // Invoke search function

In each iteration, I aim to handle scenarios where certain loops detect the presence of presale information. If presales exist, specific data should be utilized; otherwise, default values should be applied as indicated in the else statement.

Although the line

e.innerHTML = json.page.totalElements + " events found.";
functions correctly in displaying the count of retrieved events, I face challenges in showing data in the table due to the
Uncaught TypeError: json.has is not a function
error related to json.has("presales").

Please refer to this screenshot for visual clarification of the problem. Thank you for your assistance!

Any guidance or support would be highly appreciated. Thank you sincerely!

Answer №1

After some experimentation, I decided to change the json.has() method to

json._embedded.events[i].sales.hasOwnProperty('presales')
. It worked perfectly fine up until Loop #4. However, as soon as it reached Loop #5, an issue arose -
Uncaught TypeError: Cannot read property 'startDateTime' of undefined at showEvents (apijs.js:41)
. Any suggestions on how to tackle this hurdle?

Check out the screenshot below.

Take a look at this screenshot for reference.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Verifying the type and quantity of an item

Looking at a piece of code where a specific condition is being checked, I'm curious to know why someone might want to skip this particular condition. var number = /^\d+/; var type = Object.prototype.toString.call(obj); for(var key i ...

Is there a way to trigger a function for both a left and middle click at the same time?

Check out this code snippet: $('a').on('click', function(){ myfunc($(this)); }); function myfunc(el){ console.log('Either left or middle click clicked on the link'); } a{ cursor: pointer; } <script src="https://aj ...

Using NodeJS and EJS to Display MySQL Query Results

I am currently working on a project where I need to display data retrieved from a MySQL query in an HTML table. However, when I attempt to do so, I encounter the following output: [object Object],[object Object],[object Object],[object Object],[object Obj ...

The carousel's slides don't behave properly when swiping or using the slider controls (next/prev)

I have recently completed the construction of a carousel with swipe/touch functionality and control buttons for previous and next slides. However, I am facing an issue with the behavior of the carousel as it seems to be sliding by 2 or 3 instead of one at ...

What is the method for transforming an array object into an object?

How can I assign the values of an array object called hello to a constant called answer, changing the key value in the process? I've considered using Object.entries but couldn't quite get it right. Is there a way to achieve this? Here is my cod ...

Adding external stylesheets or libraries in Express is a simple process that can greatly

Currently, I am in the process of developing a todo application using the express framework on a node server. The starting point for my application is an index.ejs file located in the same folder as my jquery.min.js file. However, when I attempt to include ...

The effectiveness of a promise chain is consistent, even when the return statement is subject to conditions

After reorganizing this sequence, I am perplexed at how it continues to function regardless of a conditional return statement in one of the .then sections: function addList(name) { let listObj = {}; listObj.name = name; return nameExists(name) //returns a ...

Troubleshooting Issue: Failure of Ajax Script to Display Saved Data in Edit Function

Whenever I clicked on the Edit icon in the action column of my data tables, the saved data did not display as expected. I noticed that this issue was only occurring for file input types, while it worked properly for text input types. In the Blade file Ad ...

How can you access additional fields beyond what is displayed in a dropdown select menu in React?

I am working with an array of Jsons that contain the fields ID, name, and description. My goal is to create a dropdown selection box that will show both the name and description when clicked, and then store the associated ID in the rawID state. I have been ...

Implementing the disabled attribute in input text fields with Vue.js

There are 2 URLs that I am working with: /register /register?sponsor=4 The first route, /register, provides a clean input field where users can type freely. The second route, on the other hand, pre-fills the input with a value of 4 and disables it, ...

Tips for expanding Jackson property detection in a universal manner for all types?

After discussing serialization in my previous post, I am now looking to expand my support to include the JsonFormatVisitor. My requirements remain the same: I have objects of various types (interfaces). The type of these objects is unknown beforehand. I ...

Utilizing the closest method to retrieve the form element

As I review code written by another developer, I came across a surprising method used to retrieve a form object. HTML for Login Form <form id="frm_login" action=""> <input type="text" name="username" id="username"> <input type="passwor ...

IE9 is causing a bizarre problem where the entire page is suddenly jumping. It's

UPDATE: The client has requested testing to disable the click and drag feature in IE, so replicating the bug may be difficult at this time. I apologize if this hinders the community's ability to help fix the root issue. Here's the issue: It occu ...

Puppeteer gathers data on page loading - including a comprehensive list of files loaded and their respective sizes

Is it feasible to compile a complete list of all files loaded on a webpage using Google's Puppeteer? This would include scripts, styles (excluding inline), images, videos, and audio, along with their respective sizes. If Puppeteer cannot provide this ...

The KeyboardAvoidingView disrupts the structure of the flexbox layout

Check out this code snippet: return ( <KeyboardAvoidingView style={{ flex: 1 }} behavior="padding" enabled> <View style={style.flex1}> <View style={style.imageContainer}> <Image style={style.image} ...

Tips for configuring jQtree to initially display the tree structure from the HTML source

Up to this point, I have utilized jQuery TreeView for the navigation menus on my website. However, as the main navigation menu has grown significantly in size (40869 bytes out of 67054 bytes), I am seeking a way to streamline it by using AJAX calls to fetc ...

The webpage encountered an issue while trying to load a resource: the server returned a 500 (Internal Server Error) status message, preventing the submission of the data

When I use AJAX jQuery to send data via POST, the input name does not get sent and the database shows NULL as the answer. Thank you for any assistance. Below is my JQuery code: $('#btn-save').click(function(){ $.ajax({ url: "<? ...

Wait to display the page until all AngularJS directives have finished loading their HTML content

I've encountered an issue in my AngularJS application where I created directives that load external HTML templates from another URL. The problem is that when I navigate to the page, the binding works fine but the directive's HTML doesn't loa ...

JavaScript client side event that references the sender object ID in an aspx file

Can someone provide assistance with an issue in the code block below? function(s, e) { form1.hfRaiseEvent.value = s.ID; } This particular function is triggered when the Client Side Click Event occurs. From my understanding, s refers to the Sender Obj ...

What is the process for decoding data into an embedded struct?

Is there a way to utilize .Decode() on a response body to populate a struct without needing to determine the specific type of struct beforehand? I have a versatile struct called Match, designed to store information about various games, like a match in For ...