Utilizing Vue.js to compare two arrays and verify if the results are identical

I am in the process of developing a theater app that requires me to work with JSON data consisting of two arrays: Sections and Groups. While I have successfully loaded both arrays into my Vue app, I now need to compare them to find matches. The first array contains information about seats, while the second array holds details on reservations. Utilizing the v-for attribute, I can loop through the sections array and display the seats accordingly. However, my challenge lies in comparing array 1 with array 2 and applying certain classes to indicate if a seat is occupied or not.

  • A section includes attributes such as name, rows, and seats.
  • A group consists of a name, rows, and a seat.

Based on my analysis, I believe I should cross-check if the seat in a specific row aligns with the section's name. If there's a match, I can assign the ID as a class to the seat.

Here is the JavaScript code snippet used to load the JSON data:

export default {
    name: 'app',
    data() {
        return {
            json: [],
        }
    },

    mounted() {
        axios({
            method: "GET",
            "url": url
        }).then(result => {
            this.json = result.data;
        }, error => {
            console.log(error);
        });

    },

}

Below is the HTML loop designed to display sections, excluding the occupied seats:

<div v-for="(item, index) in json.sections" v-bind:key="index">
  <h3>{{ item.name }}</h3>
    <div v-for="(item, index) in item.rows" v-bind:key="index">
      <div class="rownr">{{ item.row }} </div>
        <div v-for="(item, index) in item.seats" v bind:key="index"v-bind:class=item.rank>
          <div :class=item.row>
            <div v-for="(group, index) in json.groups" v-bind:key="index">
              <div v-for="(group, index) in group.seats" v-bind:key="index">{{ item.seat}}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
</div>

The excerpt from the JSON file looks like this:

{
"sections": [{
        "name": "balcony",
        "rows": [{
                "row": "1",
                "seats": [{
                        "seat": "1",
                        "rank": "rank1"
                    },
                    ...
            },

        ]
    },
    {
        "name": "main hall",
        "rows": [{
                "row": "1",
                "seats": [{
                        "seat": "1",
                        "rank": "rank1"
                    },
                    ...
            {
                "row": "2",
                "seats": [{
                        "seat": "1",
                        "rank": "rank2"
                    },
                }
],
"groups": [{
        "id": "1",
        "seats": [{
                "section": "main hall",
                "row": "2",
                "seat": "4"
            },
            ...
 ]}

Answer №1

If you need to update the json variable to include additional properties in the seats section based on the groupId found in the groups section, you can use the following code:

json.groups.forEach( ({id, seats}) =>
    seats.forEach( ({section, row, seat}) =>
        json.sections.find(s => s.name == section)
            .rows.find(r => r.row == row)
            .seats.find(s => s.seat == seat)
            .groupId = id
    )
);

This code assumes that all seat references in the groups part are present in the sections part. If not, an exception will occur.

You can then check for the presence of the groupId property during rendering and adjust your display accordingly.

Dealing with Invalid Seats

If there are invalid references in your data where sections, rows, or seats from the groups part do not match those in the sections part, you can use this more detailed code snippet to identify the missing elements:

json.groups.forEach( ({id, seats}) =>
    seats.forEach( ({section, row, seat}) => {
        const foundSection = json.sections.find(s => s.name == section);
        if (!foundSection) throw "Section " + section + " is referenced in groups but does not exist in sections";
        const foundRow = foundSection.rows.find(r => r.row == row);
        if (!foundRow) throw "Section " + section + ", row " + row + " is referenced in groups but does not exist in sections";
        const foundSeat = foundRow.seats.find(s => s.seat == seat);
        if (!foundSeat) throw "Section " + section + ", row " + row + ", seat " + seat + " is referenced in groups but does not exist in sections";
        foundSeat.groupId = id;
    })
);

Use this information to correct your input data so that every seat has a corresponding match.

Rendering Instructions

To render the data with conditional logic using v-if and v-else, you can follow this example:

{{ item.seat }}
<span v-if="'groupId' in item">occupied</span>
<span v-else>free</span>

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

Utilizing PHP and jQuery to dynamically populate Google Maps with multiple markers

I am currently working on integrating a Google map with a database to dynamically display multiple markers using PHP and MySQL. Below is the code I have been using: <?php //This section retrieves data from the database for later use in jQuery //CREATE ...

Parsing a JSON file based on certain conditions

{ "RouteTables": [ { "Associations": [], "RouteTableId": "rtb-ce3c7daa", "VpcId": "vpc-87cf4de3", "PropagatingVgws": [], "Tags": [ { "Value": "I ...

adding a touch of flair to a form input that doesn't quite meet the

My goal is to have a red background appear when an input is invalid upon form submission. I attempted the following code: input:invalid { background-color:red; } While this solution worked, it caused the red background to show up as soon as the page l ...

utilize the useRef hook to display the total number of characters within a text area

Introducing the following component: import React from 'react'; export interface TexareaProps extends React.TextareaHTMLAttributes<HTMLTextAreaElement> { maxLength?: number; id: string; } export const Textarea = React.forwardRef( ( ...

JavaScript saves all URLs using a consistent format (http, https, www.)

As a junior backend developer, my experience with JavaScript is limited. I am attempting to standardize the format of stored URLs as shown below: www.hello.com hello.com http://hello.com https://hello.com Currently, if I input hello.com, it automatically ...

How can one retrieve data from two distinct API routes within a Next.js application?

Currently, I am working with Next.js and facing a challenge in fetching data from two different API routes simultaneously. My intention is to retrieve this data within the getServerSideProps function. The first dataset that I require can be found at the e ...

Guide on replacing buttons with <a> tags in express.js posts

I've incorporated handlebars as my chosen templating engine and I'm utilizing buttons to trigger app.post() in my JavaScript file. <form method="POST" action="/smo_assessment"> <div class="container" id="div1"> <h3 id="header" ...

Tips for preventing FormLabel components from turning blue when a radio button is selected

Currently, I am working on a Reactjs project that utilizes Material Ui components. In this project, I am tasked with creating a form to generate a new event where users can select the event location type from three options - In-Person, Hybrid, and Virtual ...

Using jQuery to trigger alert only once variable has been updated

I have a question that may seem too basic, but I can't find the solution. How do I make sure that the variables are updated before triggering the alert? I've heard about using callbacks, but in this case, there are two functions and I'm not ...

Struggling to run npm build in Next.js project due to webpack errors?

After months of developing this application, I encountered a frustrating error when attempting to run npm run build for the first time today. Despite removing next-transpile-modules from my next.config.js and taking various troubleshooting steps like delet ...

Utilize a PHP-AJAX request to retrieve JSON data and then transfer the data to JGauge.js in order to display the value

scenario where I need to transfer an ajax-called value to another script (specifically a widget script) within the same file, I have managed to successfully execute the ajax call and implement a justgage widget on a single page. While I can effectively dis ...

Retrieve data from a MySQL database and input it into a PHP URL

I am having trouble retrieving a username from the database to fetch the corresponding JSON data for that user. The current code I have implemented is generating a 500 error, possibly due to some issue with $json variable... Could someone offer assistance ...

Encountering difficulties in storing array data into MongoDB collection

I am facing an issue with connecting to two different MongoDB instances using different URLs. One URL points to a remote connection string while the other one is for a local MongoDB instance. Initially, I establish a connection to MongoDB using MongoClient ...

The resolution of the dynamic imported Vue component was not successful

Upon attempting to import a dynamic component using the import() function, I encountered the following error: [Vue warn]: Failed to resolve async component: function () { return __webpack_require__("./src/components/types lazy recursive ^\\. ...

Tips for identifying incognito mode and launching a fresh tab within an already open incognito window

I may not be a professional developer, but I created a Chrome extension app. You can check it out here: Link to Chrome Extension This app currently adds a context menu and opens a new tab in Chrome. However, one of my users has asked me to make the app wo ...

Tips for resolving a jspdf naming collision situation

In my react app, I am utilizing various jsPDF libraries as shown below: For exporting tables as HTML: import jsPDF from 'jspdf'; import "jspdf-autotable"; For converting SVG to PDF: const svg2pdf = require('svg2pdf.js'); con ...

Traveler encountering Flask website displaying 500 error on Dreamhost platform

I'm struggling to configure Passenger with Flask on my DreamHost server. The Flask site is running inside a virtualenv with Python 3.5.2. The goal is to take input from a query string in the URL, parse a JSON file on the server, search for the given q ...

Switch the toggle to activate or deactivate links

My attempt at coding a switch to disable and enable links using CSS is functional in terms of JavaScript, but the appearance is not changing. I am lacking experience in this area. Here is my HTML Button code: <label class="switch" isValue="0"> ...

Tips for preventing the creation of an element in AngularJS

When working with Angular, I encountered an issue with creating an <iframe> element only upon user interaction. Initially, I simply placed the element on the page and used the ng-if directive to bind its presence to a boolean in my model. However, I ...

SinonJS - Retrieving Property Value Prior to Stub Invocation

Currently leveraging sinon.js for stubbing functionalities where it is feasible to stub and spy on methods but not properties based on my observations. I'm interested in knowing if there's a way to verify whether state.searchText gets assigned t ...