Transform JSON data into HTML format while excluding particular values

I recently integrated a JSON API that fetches event data. Here's a snippet of the JSON structure:

{
   "id":1,
   "status":"ok",
   "start":{
      "date":"2021-01-16"
   }
}

To display this data in HTML, I wrote this simple script:

var url = 'https://api.com/calendar.json';

$.getJSON(url, function(data) {
  var events = data.resultsPage.results.event;
  console.log(events);
  
  events.forEach(function(item, index, array) {
    var event_month = moment(array[index].start.date).format('MMM');
    var event_day = moment(array[index].start.date).format('D');
    var event_date = '<div class="event-date">'+ event_month +' '+ event_day +'</div>';    
    var event_performer = array[index].performance[0].artist.displayName;
    var event_venue = array[index].venue.displayName;
    var event_city = array[index].location.city;
    var event_link = array[index].uri;
    var event_details = '<div class="event-location"><div class="event-city">' + event_city + '</div></div><div class="event-venue">' + event_venue + '</div><div class="event-info"><a href="' + event_link + '" target="_blank" class="btn btn--tertiary btn--small">TICKETS</a></div>';
    
    if(event_month != 'Invalid date' && event_day != 'Invalid date' && array[index].status === 'ok') {
      $('.tour-grid').append('<div class="item">' + event_date + event_details + '</div>');
    }
  });
});

The issue I'm facing now is filtering out events with a status of 'cancelled'. The current JavaScript code displays all events regardless of their status.

Is there a way to adjust the code so that only events with a 'status' of 'ok' are shown in the HTML output, and any events marked as 'cancelled' are excluded?

Answer №1

Here is a useful snippet of code:


$.getJSON(url, function (data) {
    var events = data.resultsPage.results.event;
    console.log(events);

    // Filtering out events with status "cancelled" to prevent them from rendering
    const filteredEvents = events.filter(event => event.status !== "cancelled");
    // Looping through the filtered events
    filteredEvents.forEach(function (item, index, array) {
    ...
    });
  });

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

Verify if the element in the array is set to true

Using a simple boolean in a condition is straightforward : var running = true; if(running) {/*do something*/} But what about using a boolean array? Can it be done like this: var running = [false,false,true,false]; if(running[]){/*do something*/} Curren ...

Unable to correlate the response with the designated object

I'm currently facing an issue while attempting to utilize Angular4 HttpClient with an observable object that I've defined. My challenge lies in mapping the response to the designated object. The root of the problem appears to be related to my us ...

How to Retrieve Video Length using AJAX in the YouTube API

I have been working on a script to fetch the duration of a YouTube video using its id. Here is the code snippet I've written: var vidID = ""; var vidData; var vidDuration; function getResponse() { $.getJSON( "https://www.googleapis.c ...

Laravel 5.0 facing issues with AJAX requests

For my Laravel 5.0 project, I am utilizing Google API's for Google Oauth login. After successfully retrieving the email and id_token of the currently logged-in user, I aim to send this data to the SigninController to access our own API. The goal is to ...

Avoiding the use of a single or double backslash in JSON data

Trying to properly interpret a Windows path encoded in a JSON string can be tricky. The path typically looks like this: \\sys\tld\a\b\c The following Python code snippet successfully loads the JSON string with the specified ...

Changing the CSS property of a single table cell's innerHTML

I have a question that may seem silly, but I'm going to ask it anyway. Currently, I am iterating through a list of strings that follow the format "1H 20MIN" and adding them to table cells using the innerHTML property like so: for (i = 0; i < list ...

Restarting the timer in JavaScript

How can I reset the countdown timer every time a user types into an input field? I tried using clearTimeout but it doesn't seem to work. Can anyone help me with my existing code instead of providing new code? DEMO: http://jsfiddle.net/qySNq/ Html: ...

When attempting to process a JSON string with JQuery's parseJSON() method, no response or error is returned

I've spent some time searching on various forums to find a solution to my problem, but it seems that no one else has encountered it. I am retrieving a JSON string from a field in my MySQL table, which is in the following format: {"width":"10", "heig ...

In order to ensure JavaScript can be universally applied to all images, it needs to be made more generic

I have developed JavaScript functions to enable zoom in and zoom out functionality for an image through pinching gestures. Now, I aim to refactor the code below so that I can include it in a shared JavaScript file. var scale = 1; var newScale; ...

Is Implementing a Promise for Preprocessing in NodeJS Worth It?

Looking to achieve the following using NodeJS + Express: Client sends a post request with JSON document data={text: "I love Stackoverflow", shouldPreprocess: <true or false>}; Need to call an external WebSocket service for sentiment analysis on the ...

What are the advantages of passing state from child components up in React?

I have been attempting to update the state within the App component from a child component, but I am concerned that this approach may cause issues later in my application. I've experimented with passing down the setFunction to the child components an ...

A guide on triggering a function when the context changes in a React application

Can I automatically trigger a function in a component whenever the context changes? Specifically, I have a variable named isLoggedIn in the Navbar module. Whenever a user logs in, the value of isLoggedIn is updated to true. In my Blog module, how can I m ...

Combining 2 JSON files based on a specific key value using Ansible

In my scenario, there are two JSON objects provided below. The objective is to compare JSON1 with JSON2 based on the subnet value. If the subnet in JSON1 and localSubnet in JSON2 match, then I need to copy the line (useVpn) under the specific localSubnet f ...

Launch all external links in Browser (NWjs)

While attempting to create my own independent version of Google Chat using NWjs, I encountered some obstacles. When a link is opened in the NWjs window, it opens in another NWjs window instead of the default system browser, which is what I want. I attemp ...

Leveraging TypeScript enums in conjunction with React to anticipate a string prop

Trying to enforce strict typing for a Button component in React. How can I ensure a prop has a specific string value? The current effort yields Type '"primary"' is not assignable to type 'ButtonLevel' enum ButtonLevel { Primary = ...

How to dynamically disable options in a Vuetify v-select based on the type of object value

When utilizing the Vuetify v-select component and setting the prop multiple, we can select multiple values at once. In this scenario, I have a variety of recipes categorized under Breakfast or Dinner using the parameter type. The goal is to deactivate al ...

JavaScript class syntax allows for the definition of inherited instance fields

In the code snippet below, I have implemented a way to define a prototype with a simple property that can be inherited by objects using the prototype: const SCXMLState = Object.setPrototypeOf( Object.defineProperties({ addChild() { } isStat ...

Running multiple instances of setTimeout() in JQuery

I'm looking for a way to delay the execution of 10 lines of independent jQuery code with 2 seconds between each line. I initially tried using setTimeout() on each line, but is there a more elegant solution for this scenario? The jQuery DELAY method do ...

Transfer files seamlessly between different APIs

Is it possible to directly transfer thousands of files (images, pdfs) from one third-party API service to Google Drive API without the need for intermediate storage like an AWS S3 bucket? I already have authentication set up for both APIs. I am considerin ...

Efficiently making JQuery Ajax requests using HTTP Basic Authentication

I am currently experiencing challenges with implementing HTTP Basic Authentication in JQuery when communicating with a REST-based server. This server provides responses in both XML and JSON formats, but I have chosen to work with JSON format. Our authoriz ...