Attempting to implement a b-table that can manage multiple arrays within an array

This is the b-table, designed to display a column of food items

<b-table :fields="Fields" :items="ITEMS">
   <template #cell(food)="data">
        {{data.item.food}}
   </template>
</b-table>


//Column Setup
Fields() {
 return [{key: 'food', label: 'food'}];
}

The current data format looks like this:

[
    {
        "food": "taco"
    },
    {
        "food": "burrito"
    }
]

It displays the values in a single column on the table.

What I need

I want the table to be capable of handling data in this format

[
    {
        "foods": [
            {
                "food": "taco"
            },
            {
                "food": "burrito"
            }
        ]
    },
    {
        "foods": [
            {
                "food": "soup"
            },
            {
                "food": "rice"
            }
        ]
    }
]


//Column Update, may not be accurate but attempting to iterate through all "food" under each "foods"
Fields(){
      return [{key: 'foods.food', label: 'food'}];
},

This would present the data in the table the same as before, in one column.

Close to Success!


<!-- When encountering a "foods" array, iterate through all food items it contains -->

<b-table :fields="Fields" :items="ITEMS">
   <template #cell(foods)="data">
      <div v-for="entry in data.item.foods" :key="entry.food">

          <!-- **THIS TEMPLATE IS NOT FUNCTIONAL, but if it were, it would be a solution!** -->
          <template #cell(food)="data">
            {{food}}
          </template>


      </div>
   </template>
</b-table>

Answer №1

In order to populate the table with data in a single column, the method remains the same as before.

To achieve this, ensure that your items array is flattened. You can achieve this by converting the input array into a flat array within the mounted() life cycle hook and then binding it to the <v-table>.

Here is a demonstration:

window.onload = () => {
  new Vue({
    el: '#app',
    data() {
      return {
        fields: [{key: 'food', label: 'food'}],
        items: [
          {
            "foods": [
              {
                "food": "taco"
              },
              {
                "food": "burrito"
              }
            ]
          },
          {
            "foods": [
              {
                "food": "soup"
              },
              {
                "food": "rice"
              }
            ]
          }
        ]
      }
    },
    mounted() {
      this.items = this.items.map(d => d.foods).flat();
    }
  })
}
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0274776742302c342c3332">[email protected]</a>/dist/vue.min.js"></script>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c0a2afafb4b3b4b2a1b0edb6b5a580f2eef0eef0edb2a3eef2f7">[email protected]</a>/dist/bootstrap-vue.js"></script>
<link rel="stylesheet" href="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="284a47475c5b5c5a4958055e5d4d681a06180618055a4b061a1f">[email protected]</a>/dist/bootstrap-vue.css"/>
<link rel="stylesheet" href="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4c2e2323383f383e2d3c0c78627f627d">[email protected]</a>/dist/css/bootstrap.min.css"/>
<div id="app">
      <b-table :items="items" :fields="fields">
      </b-table>
</div>

Answer №2

If you're looking to create a single column table displaying a list of food names using bootstrap-vue, the data structure should be as follows...

fields: ['food'],
items: [
  { food: "taco" },
  { food: "soup" },
  // ...
]

Based on the feedback from the original poster (OP), it seems that the source data is in a different format. The task at hand is to convert the source data into a format compatible with the table. This transformation can efficiently be achieved using a computed property. The advantage here is that the transformation will be cached and remain responsive to changes in the source data.

The code snippet below demonstrates how to convert the data provided by the OP into the required format for the table:

computed: {
  items() {
    // Assuming the source data is in the format specified by the OP
    return this.sourceData.map(d => d.foods).flat()
  },
}

Here is an example showcasing the functionality of this computation:

window.onload = () => {
  new Vue({
    el: '#app',
    data: function() {
      return {
        sourceData: [],
        fields: [{ key:'food', label:'The Foods' } ]
      }
    },
    mounted() {
      this.sourceData = [
        { foods: [ { food: "taco"}, { food: "burrito"} ] },
        { foods: [ { food: "soup"}, { food: "rice"} ] },
      ];
    },
    computed: {
      items() {
        return this.sourceData.flatMap(d => d.foods);
      }
    },
  })
}
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bdcbc8d8fd8f938b938c8d">[email protected]</a>/dist/vue.min.js"></script>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="72101d1d0601060013025f04071732405c425c5e">$0r41d1c0b0a0b0c5a41404c42424f0801060a0f</a>/dist/bootstrap-vue.js"></script>
<link rel="stylesheet" href="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9efcf1f1eaedeaecffeeb3e8ebfbdeacb0aeb0aeb3ecfdb0aca9">[email protected]</a>/dist/bootstrap-vue.css"/>
<link rel="stylesheet" href="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d0b2bfbfa4a3a4a2b1a090e4fee3fee1">[email protected]</a>/dist/css/bootstrap.min.css"/>
<div id="app">
  <b-table :items="items" :fields="fields"/>
</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

Customize Bootstrap 4 Carousel: Set specific data-interval for each slide

I'm facing an issue with setting the data-interval for each slide of the carousel. I came across a JavaScript code snippet on stackoverflow, but it's not functioning as expected. (Twitter Bootstrap Carousel slide duration) In my HTML, each slide ...

Prevent the transmission of keydown events from dat.GUI to the Three.js scene to maintain event isolation

This code snippet (below) contains 2 event listeners: renderer.domElement.addEventListener("pointerdown", changeColor, false); document.addEventListener("keydown", changeColor, false); Both of these event listeners trigger a color chan ...

Angular Dynamic Alert Service

Is it possible to customize the text in an Angular Alert service dynamically? I'm looking to make certain words bold, add new lines, and center specific parts of the text. Specifically, I want the word "success" to be bold and centered, while the rest ...

When using Next.js getServerSideProps(), cookies are not accessible on the initial render after a redirect, but they become available upon refreshing the page

Within my Next.js application, I am serving cookies from the server-side API like this: res.setHeader('Set-Cookie', AJWT) res.redirect(302, '/') Now, in my index.js file, I am attempting to retrieve the cookie before the page is render ...

Using Vuejs to dynamically render a select dropdown based on the initial selection made in the first dropdown menu

I am facing an issue with two drop-down menus. The second menu's choices need to be filtered and displayed based on the selection made in the first drop-down. The RoomID value from the first drop-down is used to filter an array of objects for the seco ...

Can the environment variables from the .env package be utilized in npm scripts?

I've integrated dotenv into my cypress project and defined variables in a .env file, as shown here: USER=Admin How can I utilize the env variable USER within my npm scripts? "scripts": { "cypress:open": "npx cypress ope ...

Angular input range slider that automatically rounds decimal values from the data bindings

I've implemented a range slider within an Angular form to capture and display recorded values. <input [formControlName]="object.id" [id]="object.id" type="range" [(ngModel)]="object.answer" [step]="objec ...

Error message indicating unauthorized access while trying to implement Backbone with Slim framework and Tuupola basic authentication

I've been working on connecting my Backbone app with my server API (using Slim) and have implemented Tuppola / Basic Auth Middleware to handle authentication. The setup is fairly simple, as I'm just trying to make it work. When I access the serv ...

Is Window.navigator malfunctioning on different browsers in Mac OS?

I'm attempting to access the navigator function in my project to share a specific URL, but I'm facing difficulties accessing it on Mac OS when using browsers other than Safari. Is there a solution to this issue? Below is the function I created f ...

Show the date and time in a visually appealing way by using HTML and JavaScript in an HTA application with scrolling effects

I have the following JavaScript code to show the current date in the format Mon Jun 2 17:54:28 UTC+0530 2014 within an HTA (HTML application). Now, I would like to display it as a welcoming message along with the current system date and time: Mon Jun 2 17: ...

Attempting to retrieve a stream buffer from a function

I am currently working on creating a zip file that contains a CSV file and returning it as a buffer from a function. Below is the code snippet I have implemented: const archiver = require('archiver'); const streamBuffers = require("stream-bu ...

Creating a mat-tree component in Angular Material 6.0.1: Step-by-step guide

I am encountering an issue with my material angular mat-tree based application. The code runs without errors, but the values are not displayed on the screen. I need help resolving this problem so that I can proceed with the development. Upon opening the a ...

Transferring HTML information to Flask

I'm struggling with passing a value from a text box in a web application to a Flask application. Despite my efforts, the request object in Flask does not seem to contain the data I need. Can anyone provide assistance with this issue? Below are the rel ...

main.js vue 3 triggering a pre-create event

I am currently utilizing beforeCreate in the file main.js. Can anyone provide information on how to achieve a similar functionality in Vue 3? let app = Vue.createApp({ template: '<App/>', beforeCreate() { this.$store.commit('initia ...

Handling Circular Dependency: Injecting a Service into an HTTP Interceptor in AngularJS

I'm currently working on developing an HTTP interceptor for my AngularJS application to manage authentication. Although the code I have is functional, I am wary of manually injecting a service as I believed Angular is designed to handle this process ...

Skip using bootstrap-vue icons by utilizing the Webpack IgnorePlugin

After analyzing with Webpack bundle analyzer, I discovered that the icons from the bootstrap-vue package are a whopping 535kb in size. Knowing this, I've decided not to utilize them in my project. I attempted to exclude the entire package using a web ...

Best practices for implementing the map function with TypeScript

I'm currently working on mapping types in a DB using the Map function in JavaScript. This is my first time trying to do this, and I'm eager to learn but I've hit a roadblock. Here is the structure of the DB: const db = { data: [ { ...

Is there a way to incorporate innerhtml (or innertext) with the h() function for adding content?

Due to certain requirements, I need to utilize virtual DOM. Below is the code snippet that I am working with: // test.js import { h, ref } from 'vue' const ButtonCounter = { name: 'button-counter', props: { tag: { type: S ...

Unable to submit form data in AWS Amplify & React: The message "Not Authorized to access createRecipe on type Mutation" is displaying

I've recently set up a project using React and AWS Amplify. I've successfully added some data to DynamoDB in AWS, but when I try to submit form data from my React App, I encounter an error from the API. I'm a bit stuck on what to do next. I ...

Blurring isotopes within Google Chrome

While working with isotope in Google Chrome, I noticed that all items have the following CSS code: -webkit-transform: translate3d(properties); In Chrome, every even element [2,4,6,8,10,12,14...] appears blurred, whereas in Firefox everything looks normal ...