Leveraging dynamic keys with v-for in Vue.js

In my Vuejs project, I am currently developing a reusable table component that looks like this:

Table Component Structure:

<template>
    <div>
        <table class="table">
                <thead>
                <tr>
                    <th v-for="item in headers">
                        {{ item }}
                    </th>
                </tr>
                </thead>
                <tbody>
                <tr v-for="(item, index) in contents">
                    <th scope="row">
                        {{ index+1 }}
                    </th>
                    <td>
                        {{ item.first_name }}
                    </td>
                    <td>
                        {{ item.last_name }}
                    </td>
                    <td>
                        {{ item.username }}
                    </td>
                </tr>

                </tbody>
        </table>
    </div>
</template>

<script>
    export default {
        name: "table-type-1",
        props: ['contents', 'headers']
    }
</script>

Initially, I was able to display the table data successfully by passing the following dataset as props:

data() {
    return {
        headers: ['#', 'First Name', 'Last Name', 'Username'],
        contents: [
            { first_name: 'Jhon', last_name: 'Stone', username: '@jhon' },
            { first_name: 'Lisa', last_name: 'Nilson', username: '@lisa' },
            { first_name: 'Larry', last_name: 'the Bird', username: '@twitter' }
        ]
    }
}

However, I realized that the table might need to accommodate different data structures in the future, such as:

data() {
    return {
        headers: ['#', 'Company Name', 'City', 'Turn Over (In Billions)'],
        contents: [
            { company_name: 'ABC Infotech', city: 'New Jersey', turn_over: 100 },
            { company_name: 'Amazon Web Services', city: 'New York', turn_over: 400 },
            { company_name: 'Digital Ocean', city: 'Washington', turn_over: 200 }
        ]
    }
}

To address this flexibility, I am considering passing a keys-value pair in the headers data to map keys to specific columns like this:

data() {
    return {
        headers: [
            { title: '#', key: index, },
            { title: 'Company Name', key: 'company_name'},
            { title: 'City', key: 'city'},
            { title: 'Turn Over (In Billions)', key: 'turn_over' }
        ],
        contents: [
            { company_name: 'ABC Infotech', city: 'New Jersey', turn_over: 100 },
            { company_name: 'Amazon Web Services', city: 'New York', turn_over: 400 },
            { company_name: 'Digital Ocean', city: 'Washington', turn_over: 200 }
        ]
    }
}

Alternatively, I could simply pass the key variables like this:

data() {
    return {
        headers: ['#', 'Company Name', 'City', 'Turn Over (In Billions)'],
        keys: ['index', 'company_name', 'city', 'turn_over'],
        contents: [
            { company_name: 'ABC Infotech', city: 'New Jersey', turn_over: 100 },
            { company_name: 'Amazon Web Services', city: 'New York', turn_over: 400 },
            { company_name: 'Digital Ocean', city: 'Washington', turn_over: 200 }
        ]
    }
}

Do you have any suggestions on how I can achieve this flexibility in my table component, such as integrating these keys into the v-for element? Any advice or insights would be greatly appreciated. Thank you.

Answer №1

To iterate over each row, go through the headers, extract the key, and retrieve the content using the key:

new Vue({
  el: '#app',
  data: {
    headers: [
        { title: '#', key: 'index' },
        { title: 'Company Name', key: 'company_name'},
        { title: 'City', key: 'city'},
        { title: 'Revenue (In Billions)', key: 'revenue' }
    ],
    contents: [
        { company_name: 'ABC Infotech', city: 'New Jersey', revenue: 100 },
        { company_name: 'Amazon Web Services', city: 'New York', revenue: 400 },
        { company_name: 'Digital Ocean', city: 'Washington', revenue: 200 }
    ]
  }
})
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5523203015677b607b6466">[email protected]</a>/dist/vue.min.js"></script>

<div id='app'>
  <table class="table">
    <thead>
      <tr>
        <th v-for="item in headers">
          {{ item.title }}
        </th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="(item, index) in contents">
        <th scope="row">
          {{ index+1 }}
        </th>
        <td v-for="{ key } in headers.slice(1)">
          {{ item[key] }}
        </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

What is the best way to load a model and save it to a variable for future use?

One issue I'm facing involves loading a model in this manner: var Beech; var loader = new THREE.JSONLoader(); loader.load( "./models/trees/Beech/Beech.json", function( geometry, materials ) { Beech = addMorphTree(geometry,materials,0.5); }); and uti ...

Ref attribute in Vue 3 class is not taken into consideration

I'm completely lost here. The watch is triggering when the currentPresetName changes, and isDarkMode is being updated as well. But for some reason, it seems like the :class binding is not paying attention to my ref. It only checks it on initial load a ...

Conceal the menu in Angular Material when the mouse leaves the button

When the mouse hovers over a button, a menu is displayed on the website's toolbar. The menu is set to close when the mouse leaves a surrounding span element. Now, there is an attempt to also close the menu when the mouse leaves the triggering button i ...

What is the procedure for generating a mouse event for clicking a tab in Selenium WebDriver?

As I work with Selenium WebDriver and Java, there is a tab named PR Per Product. Under the PR Reports tab, there are multiple tabs. In the PR tab, I used: WebElement menuHoverLink = driver.findElement(By.id("ext-pr")); actions.moveToElement(menuHoverLink) ...

A versatile jQuery function for extracting values from a :input selector

Is there a universal method in jQuery to retrieve the value of any :input element? I pose this question because I have a webpage containing select and checkbox inputs, as seen in the code below: for (var i = 0; i < arguments.length; i++) { ...

Should data be stored in HTML5 using data-* attributes?

I have encountered a scenario like this: The screen contains numerous 'Rocks', each with attributes such as weight, points, and velocity. When a rock is clicked, its attributes are displayed. Currently, I have stored all the rocks' attribu ...

What is the best way to create a modal popup window using Vuejs?

<style src="./LoginButton.scss" lang="scss"></style> <i18n src="./LoginButton.txt"></i18n> <script src="./LoginButton.js"></script> <template> <div class="header-login component-same ml-10"> <span v ...

establish connections within dynamic data table entries

As a newcomer to Javascript, I've been struggling with a particular question for some time now. The challenge at hand involves a dynamic jQuery table where I aim to hyperlink one row of the table data to a .php page in order to perform certain querie ...

Troubleshooting Firebase functions that end with socket hang up error ECONNRESET

For the past two years, my Firebase Function has been successfully retrieving data from an external service with soap, parsing it, and sending it back to an Android app client. However, recently it suddenly stopped working without any changes on my part, g ...

Does NextJs <Link> not fire the beforeunload event? Wanting to warn the user before they navigate away from the page

How do I prompt the user before leaving the page? I have noticed that when the user enters the page from a standard link element, the beforeunload event is triggered when they click back. However, if the user enters the page through the NextJs Link compon ...

What could be the reason for getElementsByClassName failing to work on dynamic HTML elements?

I'm currently in the process of generating multiple dynamic HTML tables and assigning a class to each one. Here's an example: var x = document.createElement("TABLE"); x.className = "table_pos_parts"; //var row = x.insertRow( ...

Create a canvas and include input boxes in an HTML document

I'm attempting to create a canvas line diagonally above two textboxes that are also positioned diagonally (similar to Samsung's pattern passcode) when a button is clicked, but I am facing difficulties in achieving this. I have attempted to solve ...

How can Angular be used to dynamically show or hide an element based on its height?

Is there a way in Angular to display a "Read More" link once the height of a paragraph reaches 200px? I'm looking for an elegant solution. Here are my elements: <section class="mynotes" ng-if="MyController.mynotes"> <p ng-bind="MyController ...

Encountering a peculiar error while attempting to install firebase-tools

Currently in the process of deploying my application on Firebase by following a tutorial. I encountered an issue after executing the command npm install -g firebase-tools: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" d ...

The wrap() method in jQuery clones elements multiple times

I have created a simple function that wraps a div tag inside another div tag when the browser window exceeds a certain width of x pixels. However, I've encountered a strange bug when resizing the page more than once. Let me share with you the jQuery ...

Including input within a component causes the input to capture all click events

I've been working on a project where I need to create a color picker component. When you click on the .swatch element, a popover opens up with a .cover div that covers the whole screen. Clicking on the cover closes the popover, following standard beha ...

Possible revised text: "Exploring methods for verifying elements within a div using Selenium

I have a situation where I need to verify elements within a div by using the following xpaths. The xpath for each item is as follows: Item 1:- //*[@id='huc-last-upsell-rows']/div[1]/div[2]/div[1]/div/div/a/img Item 2:- //*[@id='huc-last-u ...

Filter the specific output in a generator function

I have a code snippet that I need help with. function* iterateRecord() { const db = yield MongoClient.connect(''); const collection = db.collection(''); const query = {} const cursor = collection.find(query); ...

What is the method for executing a nested query in the Parse API?

Within the user object, there is a list of features: skills: {"piano:10", "singing:5", ....}; I am looking to filter users based on their 'piano' skills. How can I achieve this? It doesn't have to be an exact match but should follow the ru ...