It appears that when using v-for, the sequence of the array is altered

Data Object:

{
    "headers": {
        "location": "Location",
        "postcode": "Postcode",
        "contributors": "Contributors",
        "contributions": "Contributions",
        "percentage": "Percentage"
    },
    "rows": [
        {
            "postcode": "3018",
            "contributors": 2,
            "contributions": 2,
            "location": "Seaholme",
            "percentage": 67
        },
        {
            "postcode": "3013",
            "contributors": 1,
            "contributions": 1,
            "location": "Yarraville West",
            "percentage": 33
        }
    ]
}

Template:

<thead>
<tr>
    <th v-for="(v, k) in data.result.headers" :key="k">
    {{ v }}
    </th>
</tr>
</thead>
<tbody>
<tr v-for="(row, i) in data.result.rows" :key="i">
    <td :key="j" v-for="(col, j) in row">
        {{ col }}
    </td>
</tr>
</tbody>

Output: https://i.sstatic.net/QeN9P.png

When it comes to aligning the table header and body in the code snippet above, there seems to be a discrepancy between the order of the headers and rows. Is there a way to ensure they always match up correctly?

Answer №1

To arrange the rows data list by order of the headers keys, you can create a computed property. Below is a potential solution:

new Vue({
  el: "#app",
  data: () => ({
    "headers": { "location": "Location", "postcode": "Postcode", "contributors": "Contributors", "contributions": "Contributions", "percentage": "Percentage" },
    "rows": [
      { "postcode": "3018", "contributors": 2, "contributions": 2, "location": "Seaholme", "percentage": 67 },
      { "postcode": "3013", "contributors": 1, "contributions": 1, "location": "Yarraville West", "percentage": 33 }
    ]
  }),
  computed: {
    orderedRows() {
      const headers = Object.keys(this.headers);
      return this.rows.map(row => 
        headers.reduce((orderedRow, key) => 
          ({ ...orderedRow, [key]: row[key] })
        , {})
      );
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <table>
    <thead>
      <tr>
        <th v-for="(v, k) in headers" :key="k">{{ v }}</th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="(row, i) in orderedRows" :key="i">
        <td v-for="(col, j) in row" :key="j">{{ col }}</td>
      </tr>
    </tbody>
  </table>
</div>

Another approach suggested by @CertainPerformance involves creating a computed property for the header keys:

new Vue({
  el: "#app",
  data: () => ({
    "headers": { "location": "Location", "postcode": "Postcode", "contributors": "Contributors", "contributions": "Contributions", "percentage": "Percentage" },
    "rows": [
      { "postcode": "3018", "contributors": 2, "contributions": 2, "location": "Seaholme", "percentage": 67 },
      { "postcode": "3013", "contributors": 1, "contributions": 1, "location": "Yarraville West", "percentage": 33 }
    ]
  }),
  computed: {
    headerKeys() {
      return Object.keys(this.headers);
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <table>
    <thead>
      <tr>
        <th v-for="(v, k) in headers" :key="k">{{ v }}</th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="(row, i) in rows" :key="i">
        <td v-for="(header, j) in headerKeys" :key="j">{{ row[header] }}</td>
      </tr>
    </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

Issue with SoundCloud Javascript SDK 3.0 failing to execute put methods

Currently, I am developing a service that utilizes the SoundCloud Javascript SDK 3.0, and I seem to be encountering issues with the PUT methods. Every call I make results in an HTTP error code of 401 Unauthorized. Below is my JavaScript code, which close ...

Struggling to retrieve data from Firebase in React Native?

It's been a challenge for me as a newcomer to React Native trying to retrieve data from a Firebase database. This is the process flow of how my data is handled: 1. A user selects locations and trip details (name, startDate, endDate) --> stored in ...

Experiencing Strange Issues with Jquery Image Carousel... Assistance Needed!

I recently created a jquery slideshow using a tutorial I found at this link: While the slideshow is functioning correctly for the most part, there is a strange issue that occurs right at the beginning when displaying the first image. Initially, the first ...

Error message on TSC Printer: ActiveXObject is not defined in Chrome

I encountered an error in Chrome saying "Uncaught ReferenceError: ActiveXObject is not defined." Here is my code: let TSCObj TSCObj = new ActiveXObject("TSCActiveX.TSCLIB") TSCObj.ActiveXopenport("TSC Alpha-2R") TSCObj.ActiveXsendcommand("SIZE 50 mm, 50 ...

When using the `console.log()` function in JavaScript, the table formatting may

I'm attempting to generate a table using JavaScript Here's the HTML for the table: <table id="rounded" runat=server summary="2007 Major IT Companies' Profit" style="position:relative;left:-45px;" > <tr> <th sc ...

When using Angular, it is important to remember that calling `this.useraccount.next(user)` may result in an error stating that an argument of type 'HttpResponse<any>' cannot be used with a 'Useraccount' balance

When attempting to use this.useraccountsubject(user) to insert information upon login, I encountered an error: ErrorType: this.useraccount.next(user) then Error An argument of type 'HttpResponse' is not allowed against a balance of 'Userac ...

Navigating through an array and Directing the Path

My array contains objects as shown below: const studentDetails = [ {id:1, name:"Mike", stream:"Science", status:"active"}, {id:2, name:"Kelly", stream:"Commerce", status:"inactive"}, { ...

Issue specific to iOS devices: AJAX-loaded HTML containing <script> tags fails to execute

The purpose of the code below is to import innerStuff.html into the content-container div. Once that is done, a script within innerStuff.html named submit_entry() is used to submit the form in innerStuff.html. Current Situation: Upon clicking the button, ...

JSON error: Unable to access property 'xxx' as it is not defined

One way I extract an attribute value is like this: item['@attr']['nowplaying'] While this method is effective when the attribute exists within the json, it throws an error if the attribute is missing: Uncaught TypeError: Cannot read ...

Unable to get OverlayView() from Google Maps API to function within an AngularJS directive

My directive "map" is encountering a namespace issue. The mapInit() function is working perfectly, but there seems to be an error with my OverlayView() object that I can't seem to resolve. This is the initial step outlined in the Google documentation ...

Utilize PHP drop down menus for efficient data sorting and retrieval

On my website, there are two drop-down menus - one for courses and the other for students. I am trying to set it up so that when a course is selected from the first menu, only the students enrolled in that specific course will appear in the second dropdown ...

Ways to convert a callback-based function into a promise without losing the returned value

After being given access to this API: function doSomeWork(callbacks : { success ?: (result : SuccessCallbackResult) => void, fail ?: (result : FailCallbackResult) => void, complete ?: (result : CompleteCallbackResult) => void }) : Task ...

Analyzing JavaScript performance without causing your browser to crash

I recently experimented with profiling code and found that the most convenient method, at least on Firefox, was to utilize either console's time/timeEnd functions or profile/profileEnd methods, so I gave both a try. The issue I encountered was the li ...

Utilizing a global variable within a JavaScript function to enable its usage across different PHP pages

In my script, there is a code snippet that sets different grid sizes based on user selection. The goal is to store this selection in a variable that can be accessed in PHP code on another page to tailor the output accordingly. After attempting to add a ne ...

Error encountered while loading slick grid

I followed the tutorial for using recline JS, but I keep encountering this error message: Uncaught Error: SlickGrid's 'enableColumnReorder = true' option requires jquery-ui.sortable module to be loaded Here is what I have done so far : &l ...

A JavaScript popup displaying selectable options and a callback function

Is there a feature in Javascript that is similar to Java's alert builder? I need a button that, when clicked, will display an alert with various options. When an option is selected, it should trigger a callback function passing the chosen option along ...

Creating a fresh 2-dimensional array by extracting specific information from an existing array

If I have a scenario with a 2d array structured as follows: [ [0,1,4,2,2,5,5,0], [1,1,4,4,2,2,5,3], [1,6,6,6,7,7,3,3] ] And if I want to create a new 2d array by abstracting the identical numbers like shown below: {any one of these} [ [0,1], [1, ...

Exploring the possibilities of incorporating the web3.js library into Vue.js

Looking to implement web3.js with Vue.js for interacting with ganache and processing transactions. Unsure of where to incorporate the code for establishing a connection and executing transactions. ...

Discovering a precise object from an array in MongoDB

Let's consider a scenario with the following MongoDB document: { "_id": { "$oid": "628f739398580cae9c21b44f" }, "place":"Amsterdam", "events": [ { "eventName": ...

Issue encountered with the @babel/plugin-proposal-private-property-in-object package persists despite successful installation

Every time I try to run my Nuxt app, an error pops up: Error: [BABEL] C:\Users\my.name\Projects\blabla_project\.nuxt\client.js: --- PLACEHOLDER PACKAGE --- The @babel/plugin-proposal-private-property-in-object version being i ...