Determining the Next Available Date from JSON Data

I have a task of using a JSON response from the Eventbrite API to showcase the upcoming event tour date. The goal is to automatically calculate this date based on the current time, identifying the next event after the current moment.

Below is the JSON response I need to dissect:

https://jsfiddle.net/dgc223/k9dbvzoo/

If I were to check it right now, I would expect the date on line 277 to be returned (2017-11-11T11:00:00). If checking in a few hours, the expected return should be from line 350 (2017-12-09T11:00:00), as that represents the following available date for the tour.

The current script provided (below) fetches the FIRST date in the sequence from the aforementioned JSON response. However, I require a modification to retrieve the NEXT Tour date, factoring in the present time. This enhancement will offer more detailed information to users by specifying the upcoming tour date.

<script>
  $.getJSON('eventbrite_api2.php', {
    eventid: '35719663475',
    function: 'events'
  }, function(response) {
    var date = new Date(response.start.utc); //this formats the date to local 
    time zone
    date.toString();
    event_start = date.toLocaleString('en-US', {
      weekday: 'long',
      day: 'numeric',
      month: 'long',
      year: 'numeric',
      hour: 'numeric',
      hour12: true,
      timeZone: "America/New_York"
    }); //this formats the date to eastern time zone, and makes some other formatting of the date
    var content = "<h4>" + response.name.text + "</h4><p>The next event starts " + event_start + "</p>" + "<p>" + "<img width=\"350\" src=" + response.logo.original.url + "</img>";
    $("#eventbrite").append(content);
  });
</script>

Answer №1

To streamline the process, I would exclude any events that have already occurred and focus on the first upcoming event. The function responsible for handling the response can be structured this way.

function filterEvents(response) {
  var currentDate = new Date();
  var upcomingEvents = response.events.filter(function (event) {
    // compare based on UTC time
    var eventStartDate = new Date(event.start.utc);
    return eventStartDate > currentDate;
  });
  if (upcomingEvents.length) {
    // Proceed with upcomingEvents[0]; Perform necessary actions
  } else {
    // No upcoming events found
  }
}

In JavaScript arrays, the filter function selects elements from an array based on a test function, creating a new array with only the elements that pass the test.

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

Is it possible to arrange two items in one column and the rest as columns in MaterialUI Grid?

I need help arranging my arrows in a MaterialUI grid where one points up and the other points down. How can I achieve this layout? Attached below is an image of my current setup and the desired outcome. Here is my code: <Paper className={classes.paper ...

Tips on avoiding asynchronous issues in NodeJS: Ensure task a is finished before initiating task b

I have a situation where I need to ensure that task B code only executes after task A has completed. Task A involves converting an audio file, while Task B relies on the converted audio for further processing. The issue arises because Task A saves the n ...

Ways to showcase the contents of a React JavaScript document, or more specifically, a file designed for React interpretation

After trying multiple solutions, I found a conceptual guide on How to call and form a React.js function from HTML. However, the HTML generated doesn't seem to be calling from the JavaScript file as expected. It appears identical to what is mentioned i ...

Exploring the functionality of trading-vue library in a simple setup using vanilla HTML and Vue CDN

<html> <head> <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7a0c0f1f3a48544c544b48">[email protected]</a>/dist/vue.js"></script> ...

Error encountered while merging JSON files: JSONDecodeError - Additional data found: line 2, character 1 (at 376)

As a beginner coder delving into the realm of working with json files obtained from simulations conducted in an academic setting, I often find myself faced with the challenge of handling multiple iterations within each file. Each simulation run generates a ...

Simplify your bootstrap Input field code by utilizing components or a similar method in Vue.js

Using a single file component with a pug template, I am faced with multiple input fields that have the same formatting. Here is an example: .input-group.input-group-sm .input-group-addon Purchase Price input.form-control(v-model='purchase_ ...

Node.js application encounters a challenge with Swagger UI requirement not being met

My Node.js application utilizes Electron v15.3.1 and includes a Swagger UI for OAS file viewing, specifically version 4.6.1. Due to a security vulnerability in the Swagger UI, I need to upgrade it. Initially, I attempted to resolve the issue by running np ...

What are the troubleshooting tools available in Electron for detecting errors and debugging issues?

What is the process for accessing error messages and console logs in Electron while developing? Can the logs be saved directly to a file as well? Edit: Similar to how error messages and console logs are shown in Chrome's dev tools, but within Electro ...

Custom shaped corrugated sheet in three dimensions

While constructing a house-like structure with corrugated sheets, I utilized BoxGeometry to outline the structure and adjusted vertices to create a corrugated sheet wall. I have been experimenting with creating a facade using corrugated sheets in the sh ...

how to pass arguments to module.exports in a Node.js application

I have created a code snippet to implement a Node.js REST API. app.js var connection = require('./database_connector'); connection.initalized(); // I need to pass the connection variable to the model var person_model = require('./mod ...

Placing a JavaScript button directly below the content it interacts with

I am currently working on a button that expands a div and displays content upon clicking. I am facing an issue where I want the button to always be positioned at the bottom of the div, instead of at the top as it is now, but moving it within the parent div ...

When typing in the textarea, pressing the return key to create a line break does not function as expected

Whenever I hit the return key to create a new line in my post, it seems to automatically ignore it. For example, if I type 'a' press 'return' and then 'b', it displays 'ab' instead of 'a b'. How can I fi ...

Retrieve the HTML element by providing its specific index within the DOM structure of the document

I am working with the HTML source of a document stored as a string and have the index i which indicates where an element starts within this string. I am looking to create a function called getElementByIndex(i) that will return the appropriate JavaScript D ...

Steps to retrieve specific text or table cell data upon button click

Greetings, I am a beginner in the world of html and javascript, so please bear with me :) My challenge involves working with a table in html. Each row contains a dropdown menu (with identical options) and a button. When the button is clicked, I aim to sen ...

It appears that when filtering data in Angular from Web Api calls, there is a significant amount of data cleaning required

It appears that the current website utilizes asp.net web forms calling web api, but I am looking to convert it to Angular calling Web api. One thing I have noticed is that I need to clean up the data. How should I approach this? Should I use conditional ...

Creating a three-dimensional representation by projecting onto the surface of a sphere in ThreeJS

3D animation is a realm filled with numerous terms and concepts that are unfamiliar to me. I am particularly confused about the significance of "UV" in 3D rendering and the tools used for mapping pixels onto a mesh. I have an image captured by a 360-degre ...

Increasing the margin-left automatically in Bootstrap 3.0.0

I am looking to automatically generate margin-left in the ".card" class "style" element every time a post is entered on a page. My jQuery version is 1.12.4 This is my idea: If the .card CSS style has a margin-left of 0 and width of 479px, set position to ...

Converting a JSON object that is created dynamically to XML in node.js

Is there a way to convert a dynamically created JSON object into XML using node.js? I am tasked with generating JSON objects dynamically based on available data, which includes nested lists of objects. var Obj = { root: { Door_Keeper: { ...

Executing a Callback in Node with Redis Publish/Subscribe

Is it possible to implement callback with the PubSub design pattern in Node Redis? For example: server.publish("someChanel", someData, function(response) { // Expecting a response from client }); client.on('message', function(channel, data, ...

Save form data in an array of multiple objects and store it in JSON format

In my form, I have divided the fields into 3 pages with different attributes. Within my controller, I am able to convert the data into JSON format using the following code: Controller Code $input = $request->all(); unset($input['_token&a ...