Display two elements within a single table column by utilizing an array in Vue.js

I have a requirement to display 2 items from an array in one table TD ( column ). Below is the example mock data provided:

agendas: [
        [
          {
            tag: 'p',
            class: 'm-agenda__date',
            value: 'Tue, 12 Oct'
          },
          {
            tag: 'p',
            class: 'm-agenda__time',
            value: '8am - 12pm',
          },
          {
            tag: 'h3',
            class: 'm-agenda__subheading',
            value: 'Subheading of the Sub-Section'
          },
          {
            tag: 'p',
            class: 'm-agenda__description',
            value: 'Ipsum dolor sit amet, consectetur adi piscing elit duis volutpat, urna in. Lorem ipsum dolor sit amet.'
          }
        ]
      ]

Below is the Vue structure being used:

<table class="m-table__table">
      <tbody>
        <tr
          v-for="(agenda, index) in agendas" :key="index"
          class="m-table__row"
        >
          <td class="m-table__column" v-for="(column, index) in agenda" :key="index">
           <template
            v-slot:column='{ column }'
           >
            <template v-if="column.tag">
             <tag
              :is="column.tag"
              :class="column.class"
             >
              {{column.value}}
             </tag>
            </template>
           </template>
          </td>
        </tr>
      </tbody>
    </table>

At present, the data from the mock is displayed in 4 td's, but there is a request to combine the last 2 objects of the array into a single td.

Answer №1

If you're looking to implement something similar, you can start with the following code snippet and adjust it as needed for your specific project requirements.

Since I'm not utilizing VueJS in this example, there may be more optimal solutions available within the framework that I'm not familiar with.

new Vue({
  el: "#app",
  data: {
    agendas: [
      [{
          tag: 'p',
          class: 'm-agenda__date',
          value: 'Tue, 12 Oct'
        },
        {
          tag: 'p',
          class: 'm-agenda__time',
          value: '8am - 12pm',
        },
        {
          tag: 'h3',
          class: 'm-agenda__subheading',
          value: 'Subheading of the Sub-Section'
        },
        {
          tag: 'p',
          class: 'm-agenda__description',
          value: 'Ipsum dolor sit amet, consectetur adi piscing elit duis volutpat, urna in. Lorem ipsum dolor sit amet.'
        }
      ]
    ],
  },
  methods: {
    slice(agenda) {
      return agenda.slice(Math.max(agenda.length - 2, 1));
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <h2>Agendas</h2>
  <table>
    <tbody>
      <tr v-for="(agenda, index) in agendas" :key="index" class="m-table__row">
        <template v-for="(column, index) in agenda">
          <td class="m-table__column" v-if="(index < agenda.length - 2) && column.tag" :key="index">
            <tag :is="column.tag" :class="column.class">
              {{ column.value }}
            </tag>
          </td>
        </template>
        <td class="m-table__column">
          <tag v-for="(column, index) in slice(agenda)" v-if="column.tag" :key="index" :is="column.tag" :class="column.class">
            {{ column.value }}
          </tag>
        </td>
      </tr>
    </tbody>
  </table>
</div>

Answer №2

Hello everyone, I made some modifications to this code snippet.

I decided to take a different approach by creating a computed property that transforms the array data in a way that maintains the same outcome.

    
        new Vue({
          el: "#app",
          computed: {
    transformedAgendas () {
      return this.agendas.map(agenda => {
        return agenda.reduce((ret, current, index, originalArray) => {
          if(index === (originalArray.length - 1)){
            return ret;
          } else {
            if (index < (originalArray.length - 2)){
              ret.push(current)
            } else {
              ret.push([current, originalArray[index + 1]])
            }
          }
        return ret
        }, [])
      })
    }
  },
          data: {
            agendas: [
              [{
                  tag: 'p',
                  class: 'm-agenda__date',
                  value: 'Tue, 12 Oct'
                },
                {
                  tag: 'p',
                  class: 'm-agenda__time',
                  value: '8am - 12pm',
                },
                {
                  tag: 'h3',
                  class: 'm-agenda__subheading',
                  value: 'Subheading of the Sub-Section'
                },
                {
                  tag: 'p',
                  class: 'm-agenda__description',
                  value: 'Ipsum dolor sit amet, consectetur adi piscing elit duis volutpat, urna in. Lorem ipsum dolor sit amet.'
                }
              ]
            ],
          }
        })
    
    
    
        <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    
        <div id="app">
          <h2>Agendas</h2>
          <table>
      <tbody>
        <tr v-for="(agenda, index) in transformedAgendas" :key="index" class="m-table__row">
          <template v-for="(column, index) in agenda">
            <td class="m-table__column" v-if="(!Array.isArray(column)) && column.tag" :key="index">
              <tag :is="column.tag" :class="column.class">
                {{ column.value }}
              </tag>
            </td>
            <td class="m-table__column" v-else :key="index">
              <tag v-for="(column, index) in column" :key="index" :is="column.tag" :class="column.class">
                {{ column.value }}
              </tag>
            </td>
          </template>
        </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 transfer form data to another function without causing a page refresh?

Currently, I am in the process of developing a series of web applications using REACT JS. One specific app I am working on involves a modal that appears upon a state change and contains a form where users can input their name along with some related data. ...

Are you in need of a JavaScript data validation tool?

Trying to find a library that can validate input in a specific format, such as: { points: array of { x: positive and less than 20, y: positive and less than 15 } } Ideally, it should work on both server and client sides and either return a boolean or th ...

What is the best way to position a <td> element within a table row underneath another <td>?

Looking for a solution to ensure Content 3 appears below Content 2 in this block of HTML. Content 1 is extensive and extends far down the page. <table> <tr> <td>(Content 1)</td> <td>(Content 2)</td> ...

What is the best way to load $cookies into an Angular service?

After defining an Angular service where I need to access a cookie, I noticed that the $cookieStore is deprecated and that it's recommended to use $cookies instead. This is how my service is set up: 'use strict'; var lunchrServices = angul ...

Adjusting the outline color of a Material UI Select component in outlined mode to a different color when the dropdown is activated (currently shown as blue)

Is there a way to change the outline color of Material-UI select component outlined variant correctly? I need help changing the default blue color to red, any assistance would be greatly appreciated Click here for an image reference Reference code snippe ...

Encountering an issue with Vue 3 Composition API and Vue Router 4 navigation guards causing errors during implementation

I recently encountered an issue with my Vue-router 4 navigation guard that caused errors related to 'undefined (push)' from the Pinia store when I tried to use router.push('/'). Below is a glimpse of the relevant code snippet: import { ...

Using Selenium WebDriver to handle Angular requests in Java

I am currently developing tests for an angular-based application and I find myself in need of assistance. The specific task at hand involves creating a mechanism that will wait until all pending requests within the application have been processed before pr ...

Are there any creative methods for structuring Node.js Alexa code efficiently?

I'm looking for a more organized approach to managing my Node.js Alexa code. With the increasing number of intents in my interaction model, the lines of code in my lambda's index.js have become difficult to manage. Can someone provide an example ...

Is it possible to replicate an HTML table using JavaScript without including the headers?

Discover a JavaScript snippet in this stack overflow post that allows you to create a button for automatically selecting and copying a table to the clipboard. When pasting the data into an Excel template, my users prefer not to include the header informat ...

In order to enhance user experience, I would like the tabs of the dropdown in the below example to be activated by

function openCity(evt, cityName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } ...

My Vuejs project is becoming overwhelming due to the excessive number of watchers, making it difficult to scale the code

Looking for a way to streamline and scale down this code: (including snippets for illustration purposes) hoodiesml: false, hoodiemed: false, hoodielrg: false, hoodiexlrg: false, hoodiexxlrg: false, hoodiesmlqty: 0, hoodiemedqt ...

Positioning of the dropdown in Material UI AutoComplete menus

Is there a way to turn off autocomplete auto position? I would like the autocomplete options to always appear at the bottom. Check out this link for more information! ...

Pass an array using AJAX to my Python function within a Django framework

I am attempting to pass an array to my python function within views.py, but I am encountering issues. It consistently crashes with a keyError because it does not recognize the data from js. Code: Python function in views.py: def cargar_datos_csv(request ...

Navigating to a different page using the browser address bar causes the context to be reset

Upon receiving the user's data from the API on the login page, it is set in the user context. Subsequently, upon redirection to the AdminPanelApp, the data within the user context is displayed accurately. However, if I am in the AdminPanelApp and navi ...

Using Javascript to trigger form submission using arrow keys

There are four forms displayed on a single page, and I want each form to be submitted based on the arrow key that is pressed. <form name='go_north' action='' method='post'> <input type='hidden' name=' ...

Encountering a "Text creation error" while trying to run a three.js demo on Microsoft Edge using the WebGL context

When attempting to run three.js on Edge, an error message appears stating 'text could not be created. Reason: Could not create a WebGL context.' Even after trying to execute the official three.js example on Edge, the same error persisted, while ...

Tips for triggering an error using promise.all in the absence of any returned data?

I'm dealing with an issue in my project where I need to handle errors if the API response returns no data. How can I accomplish this using Promise.all? export const fruitsColor = async () : Promise => { const response = await fetch(`....`); if( ...

import a file based on a specific condition in a Next.js application

Within my next.js + express.js (with a custom server within next) application, the following flow occurs: A user chooses a parameter from a dropdown menu. After selecting the parameter, a backend process is triggered. 2.1. Based on the selected parameter, ...

The combination of Node.js module.exports and shorthand ternary operators for conditional statements

Can you explain the purpose of this line 'undefined' != typeof User ? User : module.exports and why is everything enclosed within (function(){})? I am having trouble understanding its significance. This code snippet is extracted from a library f ...

validate the existence of the username upon submission of the form

Here is some code that I have written. .js $(document).ready(function() { $("#username").focusout(function() { $.ajax({ type:'post', url:site_url()+'/client/checkUserName', data:{&apos ...