Exploring nested arrays in VueJS

When working with a prop that contains an array within an array, I find myself having to iterate through multiple v-for statements in order to access the desired data.

Currently, my process involves cycling through the spaces array to match the ids and then using conditional v-if statements to output the specific data. The same process is repeated for the rooms array.

Is there a more efficient way to filter through arrays within arrays without relying on nested for/if statements? I have attempted to explore filters as a solution but haven't found a suitable implementation for my requirements.

Vue file:

<v-flex hidden-sm-and-down sm4 lg4 class="sidebarSticky">
     <v-layout v-for="space in spaces"
               v-if="space.id === selectedSpace"
               :key="space.id" 
     >
          <!-- 1 room details -->
          <v-flex v-for="room in space.rooms"
                  v-if="selectedRoom === room.id"
                  v-if="selectedRoom "
                  :key="room.id">
              <v-card>
                  <v-card-text>

                      <!-- room name -->
                      <h2 class="sidebarRoomName"> {{ room.name }} </h2>
                      <!-- description -->
                      <p> {{ room.description }} </p>

                   </v-card-text>
             </v-card>
         </v-flex>
      </v-layout>
</v-flex>

My Data:

 new Vue({
     el: '#app',
     data: () => ({
         selectedSpace: 0;
         selectedRoom: 1,
         spaces: [
             {
                 id: 0,
                 name: 'House in Amsterdam',
                 rooms: [
                     {
                         id: 0,
                         name: 'My epic living room'
                     },
                     {
                         id: 1,
                         name: 'My epic room'
                     }
                 ]
             },
             {
                 id: 5,
                 name: 'House in Paris',
                 rooms: [
                     {
                         id: 0,
                         name: 'My epic bathroom'
                     }
                  ]
              }
           ]
        })
    })

The code snippet provided may appear straightforward, but managing larger datasets can pose significant challenges.

Answer №1

Ah yes, please avoid using v-for in that way. It's better to create computed properties and utilize Array.filter(). Then you can simply reference these computed properties in your template.

computed: {
    selectedSpaceObj() {
        return this.spaces.filter(aSpace => aSpace.id === this.selectedSpace)
    },
    selectedRoomObj() {
        return this.selectedSpaceObj.rooms
            .filter(aRoom => aRoom.id === this.selectedRoom)                
    }
}

Doing everything in JavaScript will result in clearer code, and you'll likely find yourself reusing these computed properties frequently. For instance, with selectedRoomObj, you could just rely on the existing selectedSpaceObj.

To enhance readability and avoid long accessors, consider creating space and room components. If you're dealing with nested v-for loops, it's a good indication that componentization is needed.

The challenges you're facing may prompt a reassessment of your data structure. Maybe it would be beneficial to store selection information directly within the room and space objects? Or perhaps consolidating all rooms under one root level array, with references to spaces, would make more sense?

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

Guide on choosing a date from a datepicker that is always 21 days ahead of the current date using Selenium and Java

Here is the code snippet I am working with: SimpleDateFormat df = new SimpleDateFormat("dd/MM/YYYY"); Date dt = new Date(); Calendar cl = Calendar.getInstance(); cl.setTime(dt); cl.add(Calendar.DAY_OF_YEAR, 21); dt=cl.getTime(); ...

Having trouble retrieving the necessary data to generate a menu, the getStaticProps function is coming back as undefined

I'm currently working with Next.js 13 & Strapi, and my goal is to create a Menu component utilizing the getStaticProps function. To achieve this, I've implemented a Layout component within the _app.js file, and nested a Menu component inside the ...

Guide on implementing a filter on an image using P5 in a React application

Seeking clarity on a specific issue, I'm using a react-P5-wrapper to create my P5 canvas in React, and I want to apply a filter to an image. Typically, in P5, this would be done with image.filter(GRAY). However, when P5 is an instance in React, I can& ...

Executing a script programmatically using an NPM package

I'm in the process of developing a package that relies on an external command tool called plop js. In my package.json, I aim to include a binary that points to an index.js file. "scripts":{ "plop": "plop" }, "bin": { "my-command": "ind ...

What could be the reason for the Nextjs fetch request returning undefined data?

Here is the code snippet for my GET request in the API section: export default async (req, res) => { const { query: { className }, method } = req; switch (method) { case "GET": try { const classDetail = await Class.findO ...

Warning: Potential critical dependency detected while utilizing react-pdf package

When attempting to showcase a PDF on my react application, I encountered the following warning: /node_modules/react-pdf/node_modules/pdfjs-dist/build/pdf.js Critical dependency: require function is used in a way in which dependencies cannot be static ...

Repurposing React key usage

section, I am curious to know if it is standard practice to reuse a React key from one component to another. For instance, in the Row component, the key obtained from the Column component is reused for mapping the children of Row. const Table = props =& ...

Develop your personalized Winston logging files

Check out this configuration for a Winston logger: var winston = require('winston') var systemLogger = new (winston.Logger)({ transports: [ new (winston.transports.File)({ name: 'system-file', // log which stores all ...

Explore how to set up Express with React without resorting to using create-react

I am familiar with the react and Node.js Express bundle, but I require assistance. While this question may have been posed by someone else before, I have not come across a similar query within the same framework. The specific question is: How can queries ...

Utilize jQuery to locate a specific value within a collapsible Bootstrap 4 table

Is it possible to use a Bootstrap 4 table inside a collapse? I need to search for a specific value in the table and if the value is found, I want to open the collapse and display the row containing that value. <div id="collapseStudents" class="collapse ...

The AMP HTML file is unable to load due to the robots.txt file on https://cdn.ampproject.org restricting access

I've been trying to fetch and render my AMP HTML files individually, but they all seem to be encountering the same issue. According to the Search Console report, it says "Googlebot was unable to access all resources for this page. Here's a list: ...

Executing a MongoDB query can only be successful by utilizing the copy and paste method

Recently, I encountered an unusual issue with MongoDB while attempting to query the database. Specifically, when running a query like db.departments.find({"key": "MEL 301"}), it returned no results. The MongoDB database is hosted on mLab, allowing me to v ...

Utilizing Ajax with the navigation of back and forward buttons

As I embark on the journey of developing a new application, I am determined to embrace a full ajax style approach :) My weapon of choice for ajax requests is Jquery. The main JS file will receive variables from the link that was clicked and based on those ...

invoking both componentDidMount and componentDidUpdate within the identical code block

componentLifeCycleMethod() { let data ; axios.get('http://localhost:8000/wel/') .then(res => { data = res.data; this.setState( { details: data }); }) .catch(err => {}) } I am looking to opt ...

Having trouble showing my Google map using canvas

Can anyone help me with this issue that I'm facing? I am working on a JavaScript web page and trying to show a Google map (Google API) along with a canvas tag in the html body. Currently, the map and canvas are only displaying separately. https://i ...

Generate a D3.js vertical timeline covering the period from January 1, 2015 to December 31, 2015

I am in need of assistance with creating a vertical timeline using D3.js that spans from the beginning of January 2015 to the end of December 2015. My goal is to have two entries, represented by colored circles, at specific dates within the middle of the t ...

Sync Data Automatically from SQL Database

For the past two months, I've been researching how to achieve an effect similar to the auto-updating sales on the page. So far, I haven't had any luck. I do have a PHP file that counts the number of results in a database and displays them as a n ...

How can I alter "diffuseMap" and "roughnessMap" in Three.js to become "cubeMap"?

I have a specific code snippet that I am trying to work with: var container; var camera, scene, renderer; let exrCubeRenderTarget, exrBackground; let newEnvMap; let torusMesh, planeMesh; var mouseX = 0, mouseY = 0; var windowHalfX = window.innerWi ...

Bootstrap Carousel unexpectedly leaps to the top of the page while moving forward

I am facing an issue where the slider jumps to the top of the page when I manually advance it. Can anyone provide guidance on how to prevent this from happening? Your help will be greatly appreciated! Below is the code snippet: <div class="row"> ...

Ways to verify if a chosen dynamic form input satisfies specific requirements

I just started learning Angular and I'm struggling with the nested JSON logic. I am aiming to create a dynamic form and found inspiration from this helpful tutorial. My goal is to implement conditional fields that only display when a specific option ...