Special VueJs rendering for JSON data retrieval from API

Here is the data I received from an API:

{
  "data": {
    "City": {
      "zip": "75000",
      "appointment": {
        "2020-10-12": {
          "08:00:00": 3,
          "09:15:00": 3,
          "10:30:00": 3,
          "11:45:00": 3,
          "13:00:00": 3,
          "14:15:00": 3,
          "15:30:00": 3
        },
      }
    }
  }
}

This information comes directly from the database. But, appointments that have already passed are automatically removed. For instance, if it's currently 1pm, any appointments prior to that time will not be displayed. To address this, I need a method for conditionally rendering appointments only if time >= the specified dates.

Below is the template in use:

<template v-for="(arrAppointmentData, strDate) in arrData['appointment']">
  <td :key="strDate" class="text-center ma-5 pa-5">
    <template v-if="typeof(arrAppointmentData) == 'object' &&  strDate > arrAvailableDates ">
      <span class="time-slot-x-small" v-for='(intCount, intIndex) in arrAppointmentData' :key="intIndex" v-if="intCount !== 0">
        {{ $moment(intIndex, ["HH:mm:ss"]).format('hh:mma')}}  <v-badge inline color="green" v-bind:content="intCount" > </v-badge>
      </span>
    </template>
    <template v-else>
      None
    </template>
  </td>
</template>

In my axios call:

this.arrAvailableDates    = objResponse.data.dates;
this.arrAppointmentsData  = objResponse.data.data;

Answer №1

To extract and parse the dates and times from the appointment object, you can utilize the Date.parse() function along with Object.entries() and Object.keys(). Here is a sample implementation:

function findAvailableSlots(appointments, expiryTime) {
  return Object.entries(appointments)
              .reduce((prev, [date, times]) => {
                if (times) {
                  times = Object.keys(times)
                    .filter((time) => Date.parse(`${date}T${time}`) >= expiryTime)
                    .reduce((filteredTimes, currentTime) => {
                      filteredTimes[currentTime] = times[currentTime]
                      return filteredTimes
                    }, {})
                }

                prev[date] = times
                return prev
              }, {})
}

Here's how you can use this function:

const availableSlots = findAvailableSlots(sampleData.data.City.appointment, Date.now())
// => {
//      "2020-10-12": {},
//      "2020-10-14": {
//        "14:15:00": 3,
//        "15:30:00": 3
//      },
//      "2020-10-22": {
//        "08:00:00": 3,
//        "09:15:00": 3,
//        "10:30:00": 3,
//        "11:45:00": 3,
//        "13:00:00": 3,
//        "14:15:00": 3,
//        "15:30:00": 3
//      }
//    }

Check out this demo for a visualization.

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

Combining Arrays in AngularJS with an owl-carousel Setting

My goal is to implement an endless scrolling carousel in AngularJS using owl-carousel. The idea is to load new items every time the carousel is fully scrolled and seamlessly merge queried elements with the existing list. However, I've encountered a pr ...

SwipeJS is not compatible with a JQuery-Mobile web application

I am currently attempting to integrate SwipeJS (www.swipejs.com) into my JQuery-Mobile website. <script src="bin/js/swipe.js"></script> <style> /* Swipe 2 required styles */ .swipe { overflow: hidden; ...

getJSON takes precedence over other tasks

I am having a challenge retrieving data in JSON format from the server and displaying it dynamically in a table. The code runs without errors and successfully fetches the data, but for some reason, nothing appears in the table. I suspect there may be an ...

Troubleshooting problem with JSON decoding in PHP and json_encode

Encountering an issue when parsing JSON received from a PHP backend. In my PHP code, I have an array that I send using json_encode: $result[] = (object) array('src' => "{$mergedFile}", 'thumb_src' => "{$thumb_file}"); echo json_e ...

Failure to receive a server response during the AJAX communication

I am facing an issue with my code that is making 3 requests to a server. The code successfully sends the request, but fails when receiving the response. I need help in skipping the first response and only getting the third one. phone.open("POST", '/& ...

Is there a way to retrieve the list element that was added after the HTML was generated?

How can I reference a list element added using the append function in jQuery within my onclick function? See my code snippet below: $(function() { let $movies = $('#showList') let $m = $('#show') $.ajax({ method: 'GET ...

The Javascript executor in Selenium is delivering a null value

My JavaScript code is causing some issues when executed with Selenium's JavascriptExecutor. Strangely, the code returns null through Selenium but a value in Firefox developer console. function temp(){ var attribute = jQuery(jQuery("[name='q& ...

Transfer JSON data from Python Requests to JavaScript within Django views.py

I have a Python script that retrieves JSON data and parses it: from django.http import HttpResponse import json, requests def fetch_data(request): context = {} platformUrl = 'https://www.igdb.com/api/v1/platforms' platformReq = requ ...

Using Angular 2 to execute an interface while making an HTTP GET request

I've managed to successfully retrieve and display data from a JSON object using *ngFor in Angular. However, I am struggling with applying an interface to the retrieved data. This is the content of my interface file: import {Offer} from './offer ...

`javascript pop up notification will only display one time`

I am currently developing a chrome extension with two different modes. When the user clicks on the icon, a pop-up message should appear to indicate which mode is active. However, I am facing an issue where the message does not always display when the pop- ...

What is the best way to incorporate a logo container and a horizontal divider into my top navigation bar using Bootstrap?

I'm currently working on designing a top navigation bar that features a logo with color #1 as the background on the left side. The logo is then separated by a grey horizontal divider, followed by color #2 representing the application name beside the d ...

AngularJS presents an error: [ng:areq] The argument 'myAppCtrl' is not recognized as a function, as it returns undefined while implementing routes with ngRoute and $routeProvider

Can anyone assist me with an error I'm encountering while setting routes on two buttons? Despite having everything properly defined, the table is not displaying any data. Your insights would be greatly appreciated. Thank you for your help. Snippet f ...

Stuck with the same icon even after a successful AJAX call

I am currently working on implementing a 'add to my list' function in my web app. The goal is to change the color of an icon when a user clicks on it, after sending the necessary data to the server. Despite successfully sending the data to the s ...

When the submit button is clicked, only the last form within the function will be submitted

I currently have a submit button that is meant for 3 different forms. When submitting, I use the following approach: restaurantCreateForm = function(){ document.getElementById("restaurant-features" ).submit(); document.getElementById("information_ ...

There seems to be an issue with this webpage - localhost has failed to transmit any data

I am currently experiencing an issue where, upon clicking on the href links, the page takes a considerable amount of time to redirect. However, instead of successfully redirecting at the end, I receive an error message stating that the page is not working. ...

Enhance user experience with Bootstrap by automatically adding a frame around a card upon clicking

Hello everyone! I am a beginner in the Angular/Web Development world and I am currently working on improving my HTML/CSS skills. While using Bootstrap in my Angular project, I ran into a challenge that I couldn't figure out on my own. I have implement ...

accessing the angular fullstack default application by authenticating via google oauth2

Currently, I have my angular fullstack application running on localhost:9000. I am trying to implement a feature that allows users to log in by clicking the "Connect with Google+" button on the login page. However, I keep encountering an error 400 with th ...

children blocking clicks on their parents' divs

I previously asked a question about a parent div not responding to click events because its children were blocking it. Unfortunately, I couldn't recreate the issue without sharing a lot of code, which I didn't want to do. However, since I am stil ...

Filtering data in VueJs using Vuetify's v-tabs feature

I am currently utilizing NuxtJs, a lightweight version of the VueJS framework. My goal is to implement a data filtering functionality based on tab clicks. The objective is to display the data in alphabetical order and filter them accordingly when tabs are ...

How can I prevent users from inputting negative numbers in a cellEditable material-table?

In my project, I am utilizing a material table with editable cells. I need to implement a restriction that prevents users from entering negative numbers in the field and displays an error validation message. How can I achieve this functionality? Check out ...