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

What is the reason for jQuery displaying undefined when attempting to retrieve a custom data attribute using .prop()?

In my dynamic HTML generated by JavaScript, the following code snippet is included: $(".task-status").live("click", function () { alert("data-id using prop: " + $(this).prop("data-id")) alert("data-id using data: " + $(this).data("id")) ...

Unable to utilize navigator.camera.getPicture in iOS while using PhoneGap Adobe Build

I've spent hours searching, trying to troubleshoot my PhoneGap app (compiled by Adobe PhoneGap Build) and I suspect there's something crucial about PhoneGap that I'm missing. I've added the following lines to the config.xml file: <f ...

What is the best way to retrieve all records from a MongoDB collection?

I am currently delving into the realm of JavaScript and MongoDB while attempting to construct a basic blog engine. My goal is to retrieve all blog posts stored in MongoDB so that I can utilize this data to populate an EJS template. Although I successfully ...

Protecting String in PHP to Utilize in JavaScript

When I receive code through AJAX, I handle it as shown below: $verifiedSubject = addslashes(htmlentities($_REQUEST['subject'])); $verifiedBody = addslashes(htmlentities($_REQUEST['body'])); $verifiedAttachment1 = addslashes(htmlentitie ...

Using innerHTML in React to remove child nodes Tutorial

I'm encountering slow performance when unmounting over 30,000 components on a page using conditional rendering triggered by a button click. This process takes around 10+ seconds and causes the page to hang. Interestingly, setting the parent container& ...

Guide on Adding a Map to a List in JavaScript

Currently, I am trying to extract data from a form and add it as a map to my list. However, an error message is displayed: Cannot read property 'url' of undefined express = require("express"); app = express(); var bodyParser = require("body- ...

Setting a proper prop path for nested data within a table component in Element UI using Vue JS

I'm currently facing an issue with form validation in a table layout using element-ui. Specifically, I am struggling to pass a valid prop to the el-form-item component. The structure of my data model is as follows: form: { invoices: [ { ...

Set the cookie to expire in 5 minutes using PHP, JavaScript, or jQuery

Is there a way to set a cookie in PHP that expires in 5 minutes? I am comfortable with the setcookie() function, but unsure about how to set the expiration time. Any explanation would be greatly appreciated. Could someone please guide me on how to achieve ...

Rendering a custom Vue 3 component as a string and then passing it to another component as a prop

Hey there coding mates! Currently diving into Vue 3 and the composition API with setup. I've been crafting a custom "Table" component to display... well, tables. It requires a prop named "data", which is an array of objects (representing rows) conta ...

Leveraging vuex in conjunction with typescript allows for efficient management of state in namespace modules,

I am currently integrating vuex with typescript and namespaces module in my project. Within this setup, I have two distinct modules: "UserProfile" and "Trips". So far, everything is functioning smoothly within the confines of each module. However, I have ...

Guidelines for creating a dynamic filter in Prisma js

I am looking to create a dynamic filter based on user input from the frontend. On mapping the data, I found that the object results appear like this: { id: '2', name: 'yuhu' } The keys 'id' and 'name' need to be dyn ...

Having trouble reaching the upload file in PHP

I am attempting to transfer files to a remote server using JavaScript, with PHP as the backend. The JavaScript code seems to be functioning properly, but on the PHP side, the $_FILES and $_POST arrays are empty. However, the $_SERVER array contains some da ...

Employing aspect.around while actively monitoring for methods invoking one another

Seeking a solution to run specific code around the put() and add() functions for Dojo stores, I encountered an issue with JSON REST stores where add() simply calls put(): add: function(object, options){ options = options || {}; options.overwrite = fal ...

Looking to showcase website HTML code by simply clicking on a banner image?

I am looking to implement a feature where banner HTML code is displayed in a popup on website when the banner is clicked. For instance, an example of a banner could be: <img src="https://myweb.com/images/banners/1.gif"> Upon clicking the banner im ...

What is the best approach for addressing null values within my sorting function?

I created a React table with sortable headers for ascending and descending values. It works by converting string values to numbers for sorting. However, my numeric(x) function encounters an issue when it comes across a null value in my dataset. This is th ...

No declaration file was found for the module named 'vue2-timepicker'

Overview I integrated the vue2-timepicker plugin into my Typescript/Nuxt.js application. However, I encountered an issue with importing vue2-timepicker. import timepicker from 'vue2-timepicker' Could not find a declaration file for module &apos ...

Enhance the functionality of Woocommerce email notifications by incorporating a customized VAT field

I have exhausted all options and tried various email hooks without success. I inherited an outdated PHP code that was developed by someone else, which I updated for new woocommerce hooks (since the code is 4 years old). Everything is functioning smoothly e ...

Is there a way to transfer the functionality of openssl_seal from PHP to NodeJS 18?

I'm looking to convert the openssl_seal() function from PHP to NodeJs. The code below is from my PHP SDK and works flawlessly, which is what I want to migrate: $ivLength = openssl_cipher_iv_length('AES-256-CBC') ?: 16; $iv = openssl_random ...

retrieving data from a different controller in AngularJS

Having an issue with passing data from rootScope.reslogin2 to scope.user. It's not displaying as expected, here is my JavaScript file: app.controller("logincont", ['$scope','$http','md5','$window','$rootS ...

What is the best way to utilize the oninput function in Jade?

input(type='range', id= 'inputSlider', min='0', max='255', value='50', step='1', oninput=showValue(this.value)) span#outputText 50 script. var socket = io.connect(); socket.on(& ...