Navigating through a nested array within a JSON object using Vue.js - a guide

I have a JSON data array that includes outer and inner subarrays. My goal is to loop through both levels and create a table. Below you'll find a snippet of the sample array:

    {
        class:'I',
        subDdiv:[
            {
                div: 'A',
                subjects:['Subject1','Subject2','Subject3']
            },
            {
                div: 'B',
                subjects:['Subject1','Subject2','Subject3']
            },   
        ]
}
    {
        class:'II',
        subDdiv:[
            {
                div: 'A',
                subjects:['Subject1','Subject2','Subject3']
            },
            {
                div: 'B',
                subjects:['Subject1','Subject2','Subject3']
            },   
        ]
}

My task now is to generate a table with row headings for Class and Div.

labels :['class','div']

The current code I've written isn't producing the desired outcome,

<el-table :data="array" style="width: 100%">
  <el-table-column v-for="label in labels" :key="label"
   :prop="label"
   :label="label">
   </el-table-column>
 </el-table>

Note: I am utilizing the Element UI Table component -

The desired table structure can be viewed here: https://i.stack.imgur.com/Nz7H7.png

However, the resulting table looks like this:

https://i.stack.imgur.com/lzWWN.png

I need assistance in iterating through the inner subDiv array and generating the correct table layout. You can access the code box here: https://codesandbox.io/s/vigilant-wildflower-zgiq2?file=/src/App.vue

Answer №1

If you want to iterate through the data in a single loop (as required by your current layout), it's recommended to flatten your data structure:

computed: {
    flattenedData() {
      return this.dataArray.reduce((prev, obj) => {
        let flattenedObj = obj.subDdiv.map(item => {
          let subdiv = {};
          subdiv["class"] = obj.class;
          subdiv["div"] = item.div;
          return subdiv
        });
        return [...prev, ...flattenedObj];
      }, []);
    }
  }

Once you have flattened the data, you can proceed with your existing code and loop through the flattened array like this:

<el-table :data="flattenedData" style="width: 100%">
      <el-table-column v-for="label in labels" :key="label" :prop="label" :label="label"></el-table-column>
</el-table>

Answer №2

If you're looking for an example using pure HTML tables, I've created a simple one that can help you understand how to achieve a similar result with your UI components library.

new Vue({
  el: "#app",
  data: {
    contents: [
     {
        class:'I',
        subDdiv:[
            {
                div: 'A',
                subjects:['Subject1','Subject2','Subject3']
            },
            {
                div: 'B',
                subjects:['Subject1','Subject2','Subject3']
            },   
        ]
      },
        {
          class:'II',
          subDdiv:[
              {
                  div: 'A',
                  subjects:['Subject1','Subject2','Subject3']
              },
              {
                  div: 'B',
                  subjects:['Subject1','Subject2','Subject3']
              },   
          ]
        }
    ]
   }
})
td, th {
  padding: 5px 20px;
}
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6711120227554951495656">[email protected]</a>"></script>

<div id="app">
  <table>
    <thead>
      <tr>
        <th>Class</th>
        <th>Div</th>
      </tr>
    </thead>
    <tbody>
      <template v-for="item in contents">
        <tr v-for="subItem in item.subDdiv">
          <td> {{ item.class }} </td>
          <td> {{ subItem.div }} </td>
        </tr>
       </template>
    </tbody>
  </table>
</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

Is it a usual technique to retrieve dynamic content using PhoneGap?

Recently, I've been utilizing phonegap for creating mobile applications on various platforms. I've noticed the need to use AJAX calls within JavaScript to fetch dynamic content. I'm curious, is it a standard practice in HTML5 apps to retrie ...

Interacting with dynamically loaded HTML content within a div is restricted

On my main HTML page, I have implemented a functionality that allows loading other HTML pages into a specific div using jQuery. The code snippet looks like this: $('.controlPanelTab').click(function() { $(this).addClass('active').s ...

Issue with Vuetify v-alert not appearing after updating reactive property

I am trying to set up a conditional rendering for a v-alert if the login response code is 401 Unauthorized. Here is how I have defined the alert: <v-alert v-if="this.show" type="error">Invalid email and/or password.</v-alert> Within the data ...

Need help setting up automatic audio playback on your Android device?

I'm aware that autoplay of audio is not supported on Android devices. However, I recently found a website that successfully autoplays music on an Android device: Can someone explain how this is being achieved? ...

Anguar server encountered a startup issue and failed to initialize

My server.js file looks like this: var express = require('express'), api = require('./api'), app = express(); app .use(express.static('./public')) .use('./api', api) .get('*', ...

Poorly formatted code in VueJS when using Visual Studio Code

After reinstalling Windows and installing Visual Studio Code along with Prettier, I am facing an issue where the formatting is not up to par. Below is an example showcasing the difference between how it looks versus how it should look. Incorrect Formatting ...

Minimal Space Separating Footer Division and Body Element

While there are numerous discussions online about fixing footer alignment issues, I've encountered a unique problem that needs addressing. The issue at hand is a 29px gap between the bottom of the footer and the <body> tag on my webpage, which ...

Struggling to display Three.js ply file on screen

I'm having trouble displaying my ply file using the three.js webgl_loader_ply example. Even though I can view the object in MeshLab when I open the ply file, it doesn't show up in the three.js example. I've tried various adjustments like zoo ...

Get the latest html content and save it as a .html file using javascript or jQuery

Looking for a way to save an HTML page as a .html file? Having some trouble with jQuery modifications not being included in the exported file? Check out the code snippet below and let me know if you can spot what's going wrong! I'm still getting ...

The vue-croppa component is showing unusual behavior, with an error message stating "Failed to mount component: template or render function not

I recently tried utilizing vue-croppa for image cropping in my project. I installed it using the npm package manager with the command: npm install --save vue-croppa However, when attempting to implement it as usual: import Croppa from 'vue-croppa&a ...

What is the best way to set the first radio button as the default selection in Material UI?

The challenge I am facing involves a set of radio buttons representing dates from today to 30 days in the future. When a radio button is selected or active, it changes the background color. However, I would like the default selection to be the first radio ...

How can I make AWS SDK wait for an asynchronous call to finish executing?

Understanding the AWS SDK documentation can be a bit confusing when it comes to making asynchronous service calls synchronous. The page at https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/calling-services-asynchronously.html states: All ...

Vue's innate lifecycle hook

I am looking for a way to automatically run a specific function as a beforeMount hook in every component of my Vue project without having to declare it individually. Essentially, I want a default behavior where if the hook is not explicitly stated in a com ...

Make window.print() trigger the download of a PDF file

Recently, I added a new feature to my website allowing users to download the site's content by following these instructions: Printing with Javascript || Mozilla Dev. Essentially, the user can print a newly formatted site stored in a hidden iframe. Now ...

Mudblazor - Tap or click within the designated area to trigger the drag and drop functionality

I have incorporated the Mudblazor CSS framework into my Blazor WebAssembly project. Within the drag and drop zone, I have included a button that is supposed to remove each uploaded image. However, when I click on the remove button, it only opens up the fi ...

Creating a specific quantity of divs with JavaScript

For the past few hours, I've been working hard to solve this problem that has really left me stumped. As far as I can tell, everything is correct. The create function is supposed to generate a certain number of divs specified by the user in an input b ...

Disable checkboxes upon page initialization

I am working with a form that includes checkboxes. Whenever the page loads, clicking on the checkboxes automatically checks them. However, I am looking for a solution where the checkboxes are disabled or not clickable during the page load process. Once th ...

Encountering a 'Module not found' error after integrating Vuetify through Vue CLI

I'm attempting to add Vuetify to a new Vue project created with the Vue CLI command vue create vuetify. However, every time I try to run the project in the browser, I encounter this issue: Furthermore, when I check the server terminal, I see the foll ...

Using JavaScript to parse Java objects into JSON data

I'm working on sending an array of POJOs as a response to an AJAX call. Within my POJO, the following toString() method is defined: @Override public String toString() { return "Expense [period=" + period + ", description=" + description + ...

Obtain the printed value of a button via PHP and manipulate it using JavaScript

I have a dynamic table that displays results from a database. <table id="table" class="table datatable-responsive"> <thead> <tr class="bg-teal"> <th>#</th> <th>Date & Time</th& ...