Creating a dynamic header in v-data-table with Vuetify - Any tips on how to achieve this?

Imagine having an array of objects that looks like this :

[{id: 1, item: 'apple', taste:'good', item2: 'papaya', taste2: 'bad'}
 {id: 2, item: 'melon', taste: 'bad'},
 {id: 3, item: 'orange', taste: 'good', item2: 'banana', taste2: 'bad', item3: 'grape', taste3:'good'} .......]

Is there a way to configure the v-data-table so that the header displays as follows?

ID | ITEM | TASTE | ITEM2 | TASTE2 | ITEM3 | TASTE3 .....

Answer №1

The headers value is a computed property that should be defined with the following code :

computed: {
        headers() {
          //set to store unique values
          let set = new Set();

          this.items.forEach(item => {
            for (key in item) {
              //adding only unique keys to the set
              set.add(key)
            }
          });
          
          //formatting the headers as required by Vuetify which 
          // should include two fields (text, value)
          return Array.from(set).map(a => {
            return {
              text: a.toUpperCase(),
              value: a
            }
          });

        }

      }

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data() {
    return {
      items: [{
          id: 1,
          item: 'apple',
          taste: 'good',
          item2: 'papaya',
          taste2: 'bad'
        }, {
          id: 2,
          item: 'melon',
          taste: 'bad'
        },
        {
          id: 3,
          item: 'orange',
          taste: 'good',
          item2: 'banana',
          taste2: 'bad',
          item3: 'grape',
          taste3: 'good'
        }
      ]
    }
  },
  computed: {
    headers() {
      let set = new Set();

      this.items.forEach(item => {
        for (key in item) {
          set.add(key)
        }
      });

      return Array.from(set).map(a => {
        return {
          text: a.toUpperCase(),
          value: a
        }
      });

    }

  }
})
<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@mdi/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="34525b5a4074001a4c">[email protected]</a>/css/materialdesignicons.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d3a5a6b6a7bab5aa93e1fdab">[email protected]</a>/dist/vuetify.min.css" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5e282b3b1e6c7026">[email protected]</a>/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e096958594898699a0d2ce98">[email protected]</a>/dist/vuetify.js"></script>

<div id="app">
  <v-app>
    <v-content>
      <v-container>
        <v-data-table :headers="headers" :items="items"></v-data-table>
      </v-container>
    </v-content>
  </v-app>
</div>

Answer №2

By utilizing the combination of .reduce(), Set(), and Object.keys(), you can extract the header as intended.

Give this a try:

const data = [
  {id: 1, item: 'apple', taste:'good', item2: 'papaya', taste2: 'bad'},
  {id: 2, item: 'melon', taste: 'bad'},
  {id: 3, item: 'orange', taste: 'good', item2: 'banana', taste2: 'bad', item3: 'grape', taste3:'good'}
];
 
const uniqueKeys = Array.from(data.reduce((a, c) => {
  Object.keys(c).forEach(e => a.add(e));
  return a;
}, new Set()));

console.log(uniqueKeys);

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

Setting the default selection in AngularJS based on the URL entered

I've encountered an issue with a dropdown menu in my AngularJS version 1.4 application. The dropdown menu contains links to different sections of the page. The problem arises when I directly enter the page URL - instead of selecting the correct link f ...

Observing changes in a parent component variable with Angular

One feature of my form is that it consists of a parent component and a child component. To disable a button within the form, I utilize a function called isDatasetFilesValid() which checks a specific variable (datasetList[i].fileValid). This variable is mo ...

Attempting to integrate a three.js OBJLoader within an HTML canvas

My issue is quite straightforward: I attempted to connect a three.js script with an HTML canvas, but I was unsuccessful and now I'm unsure how to proceed. Here is the code I have (I've already loaded the necessary scripts in the HTML head): wi ...

Updating a value within a VueJS watcher without interfering with the watcher itself

I created a quiz application using Vue where each question has its own time limit. I implemented a countdown feature with a watcher to display the remaining time on the webpage. However, I encountered an issue when updating the time limit for the next ques ...

The waypoints.js snippet seems to be malfunctioning in this specific context

After experimenting with waypoints.js (jQuery.waypoints) for some time, I've been attempting to utilize this library to incorporate animations on children elements within a specific container. Here is the approach I have taken: var waypoints = $( ...

during array iteration, the appendChild function is only executed once

Here's a simple question for all of you: So, I've got this for loop: var pNewTag = document.createElement('p'); var grabWrapper = document.querySelector('.footerInfo'); var myArray = grabWrapper.children; for ( var i = 0; ...

What is the best way to create reusable Javascript code?

Lately, I've adopted a new approach of encapsulating my functions within Objects like this: var Search = { carSearch: function(color) { }, peopleSearch: function(name) { }, ... } While this method greatly improves readability, the challeng ...

Stop the Enter key from functioning as a mouse click

Whenever an element is focused on and a mouse click action can be triggered, I've observed that the Enter key functions as if you're clicking the mouse left button. This behavior is causing conflicts in other parts of my code, so I need to find a ...

There seems to be an issue with posting JSON data correctly

Currently, I am attempting to include an object with numerous attributes within it. This is the object I am trying to use with $.post: ({"fname" : fname, "lname" : lname, "gender" : gender, "traits" : { "iq" : inte ...

How can I ensure that the Bootstrap datePicker is validated as a required field

I am using the it-date-datepicker as a calendar picker, which is a bootstrap-datepicker version based on ab-datepicker. The issue I am facing is that I need to make this field mandatory. I downloaded jquery.validate.js for this purpose but I can't see ...

The Ionic Capacitor "PushNotifications" plugin is currently not supported on Android devices

I'm encountering an issue while attempting to request permissions using the @capacitor/push-notifications plugin. I have carefully followed all the steps outlined in the README and am working with Ionic and Vue 3. Here is a snippet from my package.js ...

One more time: Utilizing AJAX to save the outcome in a variable with the help of callback (undefined)

I am facing a common problem and despite my efforts, I cannot seem to resolve it. The code snippet I have provided below is causing me trouble: function get_network_from_database(callback) { $.ajax({ type: "POST", url: "load_network.ph ...

How to Identify an Array in JavaScript using a String

I'm experiencing some challenges with retrieving a pre-declared array based on user input. This task is designed to help me grasp how to capture user feedback using an HTML drop-down and then return a value using a script. What I aim for in the secon ...

Binding events within other events can be achieved using D3

Trying to implement code from Scott Murray's book "Interactive Data Visualization for the Web" to create versatile bar graphs. Though the code successfully generates and updates graphs, it seems that the sorting functionality is not functioning as exp ...

How can I randomly choose 5 TR items and show them to the user?

How can I randomly select and display 5 questions for the user? The rest of the questions should be hidden on the page and only 5 questions should be displayed. This is a sample code. I want the user to see 5 questions out of many questions when the page ...

Oops! Issue detected: improperly configured csrf in Express JS 4

Seeking help to activate the csrf module within Express 4 for an existing project. This is the code I've implemented: var csrf = require('csurf') ... app.use(csrf()); Upon starting my application, I encounter this message: Error: miscon ...

Express.js - Unfulfilled promises cause blocks and slow down subsequent GET requests in express (Node.js)

I currently have an active express application that listens for GET requests. Whenever a GET request is made, it promptly returns a success response and triggers the function asyncForLoop(), which resolves a promise after 5 seconds. Issue: The problem ari ...

Attempting to send an identification number as the form value through a form select element, all while displaying the name of the object

Please choose a product category <select placeholder='product category' name="selected_product_category_id" value={formInput.selected_product_category_id } ...

Struggling to retrieve a global variable in JavaScript

Hey there! I'm having trouble sharing a global variable between two JavaScript files. I made sure to define the variable as global, thinking it would be accessible across both files. However, when I tried to access the messages variable in the first.j ...

Is it possible for my user to retrieve the content stored in $_SESSION without using Ajax by simply clicking a button?

I have a collection of arrays stored in the $_SESSION variable. My goal is to display the first sub-array in an HTML table and then dynamically update the table with the subsequent elements whenever the user clicks on a button. While I am familiar with a ...