Determining if data from two separate lists in Vue.js matches in order to display in the template

I need to compare two sets of data - one fetched from the server and the other being default data.

Data retrieved from the server:

[
  {
    "id": 7,
    "day": "14 April 2017",
    "time_list": [
      {
        "id": 25,
        "time": "11:00 AM",
      },
      {
        "id": 28,
        "time": "08:00 PM",
      }
    ]
  },
  {
    "id": 7,
    "day": "13 April 2017",
    "time_list": [
      {
        "id": 33,
        "time": "11:00 AM",
      },
      {
        "id": 22,
        "time": "02:00 PM",
      },
    ]
  },
]

Default data for the Vue JavaScript component:

default_time_data: ["11:00 AM", "02:00 Pm", "05:00 PM", "08:00 PM"]

In the template, I want to achieve the following:

<template>
    <div v-for="day in show_routine_data">

        Check if the time from the day.time_list matches the showTime_count

        For each default_time in default_time_data, check if any time in day.time_list is equal.

        If a match is found, display its id.
        Otherwise, show no data
    </div>
</template>

Hopefully that's clear, but feel free to ask if not. I've been struggling with this issue all morning and would appreciate your help.

Update:

The final displayed data should look like this (based on the provided data):

<ul>
    <li>
        <p>14th April 2017</p>
        <ul>
            <li><p> 25 </p></li>
            <li><p> No data </p></li>
            <li><p> No data </p></li>
            <li><p> 28 </p></li>
        <ul>
    <li>
    <li>
        <p>13th April 2017</p>
        <ul>
            <li><p> 33 </p></li>
            <li><p> 22 </p></li>
            <li><p> No data </p></li>
            <li><p> No data </p></li>
        <ul>
    <li>
</ul>

Answer №1

To efficiently render your data, it is recommended to create a computed property where you organize and format the required information. You can learn more about computed properties in the Vue.js documentation: https://v2.vuejs.org/v2/guide/computed.html

A computed property allows you to extract and manipulate specific data elements as needed.

In addition, you will need two nested v-for loops – one for iterating through blocks and another for looping through time IDs.

Here's an illustration:

new Vue({
  el: '#app',
  data: {
    myArr: [
      {
        "id": 7,
        "day": "14 April 2017",
        "time_list": [
          {
            "id": 25,
            "time": "11:00 AM",
          },
          {
            "id": 28,
            "time": "08:00 PM",
          }
        ]
      },
      {
        "id": 7,
        "day": "13 April 2017",
        "time_list": [
          {
            "id": 33,
            "time": "11:00 AM",
          },
          {
            "id": 22,
            "time": "02:00 PM",
          },
        ]
      },
    ], 
    default_time_data: ["11:00 AM", "02:00 PM", "05:00 PM", "08:00 PM"]
  },
  computed: {
    dataToRender: function() {
      return (this.myArr && this.myArr.length > 0) // if data is already fetched
        ? this.myArr.map(e => Object.assign({ day: e.day }, 
          { 
            timeList: this.default_time_data
              // if time in default array - return id, otherwise 'No data'
              .map(dt => (e.time_list.map(({time}) => time).includes(dt)) ? e.time_list.find(tl => tl.time === dt).id : 'No data')
          }))
        : []; // if data hasn't arrived - return empty array
    }
  }
});
<script src="https://unpkg.com/vue/dist/vue.min.js"></script>

<div id="app">
   <ul v-if="dataToRender.length > 0"> <!-- check if data exists -->
     <li v-for="item of dataToRender">
       <p>{{ item.day }}</p>
       <ul>
         <li v-for="time of item.timeList">{{ time }}</li>
       </ul>
     </li>
   </ul>
</div>

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

Retrieve an array from the updated scope

I need help with my code. How can I retrieve the names from an array and display them in my input box? Also, how do I get all the changed names back into the array? Thanks in advance! - Marco app.js var g[]; var names = ['John', 'Steve&apo ...

Scripting issues detected in Safari and Microsoft Edge browsers

I recently finished developing an AngularJs Application that works flawlessly on Google Chrome and Mozilla Firefox. However, upon testing it on Safari and IE-11, I encountered errors in the console. One particular piece of code that causes issues is used ...

Guide on implementing Vuetify Component Slot Function

Can someone help me figure out how to implement the v-alert dismissible component with additional functionality when the close button is clicked? According to the documentation, there is a function called toggle in the close slot that allows you to "Toggle ...

challenge with altering data in transmission when using the GET method

$('.textedit').editable('/webpage/skeleton/edit_text/text/process', { loadurl: '/webpage/skeleton/edit_text/loadraw', loaddata: {id: $(this).attr('id'), client: $(this).data('client')}, submitda ...

Deploying a Vue application to Internet Information Services (IIS) within the Default Website

I managed to successfully run a Vue app in IIS at the root level with port 8181, but now I need to set it up under the Default Web Site in IIS using port 80. To test this, I created a new website with the VS19 template (should have used Vue scaffolding, w ...

What is the process for converting a string literal into raw JSON and then storing it?

When trying to edit object values using a text input element and JSON.stringify(txt, null, 2), everything seems fine initially. However, after submitting the input, I end up with unwanted characters like "/n" and "\" within the string literal. Despite ...

The web application encountered an error: "Uncaught TypeError: Cannot read property 'map' of undefined" when trying to retrieve

Struggling with a simple API fetch, and despite checking everything multiple times, I can't seem to figure out what's going wrong. It feels like I'm missing something crucial. import { useState } from "react"; import ProductCard fr ...

An array of dictionaries that are the same except for one dictionary containing an unspecified key

A while ago, I wrote some sample code to generate Euler diagrams from an array of dictionaries. Strangely enough, it only works when the array is explicitly defined in my .js file; using input from a .json file to construct it incrementally does not yield ...

Every time I attempt to use $router push, an error is generated

I've encountered an issue while trying to push the router using vue-router. this.$router.push({ path: '/' }).catch(() => {}); The error message reads as follows: app.js:43636 Uncaught TypeError: Cannot read property 'classList' ...

A step-by-step guide on integrating drag and drop functionality for HTML elements using VueJs

Can anyone provide guidance on how to integrate drag and drop functionality, similar to JQuery, with vuejs? Specifically, I am interested in learning how to move elements within the DOM without using a plugin. Any insights or advice would be greatly apprec ...

Error in Next.js 13 due to Prisma table mapping causing hydration issues

I recently created a basic project in Next.js 13 and encountered a Hydration Error even though my project is not doing much. The code snippet below seems to be the cause of the issue: import { PrismaClient } from "@prisma/client"; export default ...

Experimenting with the testing of two distinct functions

Hello, I am new to the world of testing and I would appreciate some guidance. I have two functions that I need help with. The first function is a bits-per-second converter that converts data into a more readable format. const convertBitrate = bitrate =&g ...

What is the best way to sort through an array using JavaScript?

Here's an array for you: values = ["10%", 1000, "5%", 2000] I'm looking to split this into two separate arrays like so: percentages = ["10%","5%"] numbers = [1000,2000] How can I achieve this using JavaSc ...

What is the process of integrating data from the OpenWeatherMap API into the WindowInfo feature of Google Maps?

My current project involves retrieving weather information from the openweathermap API and displaying it in an infowindow on Google Maps. However, there seems to be an issue where I am getting data from the previous marker instead of the current one. var ...

The counter unexpectedly increments by 2 instead of 1

I'm attempting to create a counter that increases by one each time according to the code snippet below: var imnum = 0; (function changeImage() { ++imnum; $( ".slider" ).fadeOut(5000, function() { $('#home-slider-im').attr("s ...

advancement in the $.when function

In an attempt to make an AJAX call utilizing the $.when and $.then functions, I am employing these features to populate a template. During this process, I aim to display a message in a form that states: "Loading data... please wait." I have come across ...

Sending data from PHP to JavaScript using JSON encoding through POST requests

I am dealing with a multi-dimensional array that needs to be passed to a PHP script using JavaScript to parse JSON data and display it on Google Maps. I am experimenting with using forms to achieve this: <?php $jsontest = array( 0 => array( ...

Error encountered during navigation: navigator has not been defined

I encountered an issue where the page gets redirected upon form submission without triggering the catch block. However, in the backend, I am facing an error stating that the API body is not being executed. Below is the code snippet of the page: "use cl ...

Demonstrate a array of values at varying angles within a circle using the functionalities of HTML5 canvas

Looking to utilize HTML5 Canvas and Javascript for a project where I need to showcase various values (depicted by dots possibly) at different angles within a circle. For example, data could include: val 34% @ 0°, val 54% @ 12°, val 23% @ 70°, a ...

Can you confirm if the user originated from JavaScript when Ajax is sent?

Illustration: Upon using "ajax.send", the file is displayed (for example, "post.php?q=...".) However, by copying the specific "url" and pasting it into the browser with the same parameters, access can also be gained. Hence, is there a way to prevent this ...