What is the best way to display a intricate array in Vue.js?

This section is dedicated to inputting the name and surname of individuals. It's a tiny component I've created.

<v-row v-for="(list,i) in getList" :key="'list-item-'+i">
    
    <v-col cols="6"><v-text-field v-model="name"/></v-col>

    <v-col cols="6" > <v-text-field v-model="surName"/></v-col>

</v-row> 
data(){
    return{
          name:null,
          surName:null
       }
},

computed: {
        getList() {
            const newEntries = []

            const entries = [
                {category: 'elder', count: 3},
                {category: 'babies', count: 1},
                {category: 'children', count: 0}
            ]

            entries.map(item => {
                return item.count > 0 ? newEntries.push(item) : null
            })

            return newEntries
        }
    },

The getList variable stores an array that has been filtered based on counts being greater than 0. My issue lies in creating the correct number of components for each object in the list. For example, if there are 3 elders and 1 baby in my getList array, I should generate 4 component forms.

However, with my current solution I am only able to create 2 components – 1 elder and 1 baby. What I actually need are 3 elder components and 1 baby component.

Answer №1

Using Array.map is a way to transform one array into another. If you initially have 3 elements, you will end up with 3 elements in the resulting array. The best approach to resolving this issue largely depends on how you intend to tackle the problem of mapping all name fields to the same name variable within your component.

Alternatively, utilizing Array.reduce offers more flexibility as it iterates over all items in the original array and provides greater control over the output.

const categories = [
  {category: 'adults', count: 3},
  {category: 'teens', count: 1},
  {category: 'toddlers', count: 0}
]

const formRows = categories.reduce(
  (accumulator, item) => {
    for (let i = 0; i < item.count; i++) {
      accumulator.push({
        category: item.category,
        name: '',
        surName: ''
      });
    }

    return accumulator;
  },
  []
);

// This results in an array containing 4 items - 3 under the 'adults' category and 1 under the 'teens' category

An alternative solution involves iterating within the template itself

<template v-for="list in getList">
  <template v-if="list">
    <template v-for="i in list.count">
      <v-row :key="i">
        <!-- It's important to note that these models are all linked to the same variable, causing them to update simultaneously -->
        <v-col cols="6"><v-text-field v-model="name"/></v-col>
        <v-col cols="6"><v-text-field v-model="surName"/></v-col>
      </v-row> 
    </template>
  </template>
</template>

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

Declaration of expansion panel with additional sub-expansion panels

I'm trying to wrap my head around the concept of using the v-expansion-panels component. Do I need to declare the parent component as v-expansion-panels in order for it to contain child v-expansion-panel components, or is just using v-expansion-panel ...

"Upgrade your uploading experience with Fine Uploader 3.0 to easily customize PHP filenames post-upload

After uploading a file with a PHP script that changes the file name to an md5 value, I am having trouble retrieving the new file name. Fine Uploader, however, displays the original file name that was uploaded from the PC. I am looking for a way to retrieve ...

Validation of a string or number that is not performing as expected

I have been working with the yup library for JavaScript data validation, but I am encountering unexpected behavior. Despite thoroughly reviewing their documentation, I cannot pinpoint where I am misusing their API. When I run the unit test below, it fails ...

Is it possible to omit certain columns when extracting data from a Kendo grid?

My challenge involves extracting data from a Kendo grid using the following JavaScript call: var data = JSON.stringify($(".k-grid").data("kendoGrid").dataSource.data()) This retrieves all properties in the C# class for the records. There are three proper ...

Grunt is throwing an error message of "Cannot GET/", and unfortunately ModRewrite is not functioning properly

I've recently started using Grunt (just began last Friday). Whenever I run Grunt Serve, it displays a page with the message "cannot GET/" on it. I tried implementing the ModRewrite fix but the error persists. Any assistance would be highly appreciat ...

Retrieve a specific value from an array of objects by searching for a particular object's value

Here is an example of an array of objects I am working with: $scope.SACCodes = [ {'code':'023', 'description':'Spread FTGs', 'group':'footings'}, {'code':'024', ' ...

Need help with a countdown function that seems to be stuck in a loop after 12 seconds. Any

I am facing an issue with a PHP page that contains a lot of data and functions, causing it to take around 12 seconds to load whenever I navigate to that specific page. To alert the user about the loading time, I added the following code snippet. However, ...

Organizing JSON Objects Within Each Iteration

Greetings! Coming from a PHP background, I am currently exploring the task of grouping JSON data using JavaScript/jQuery. My goal is to group the data by extracting the SKU and then organizing the records together. While I have managed to achieve this, I a ...

Utilize [markdown links](https://www.markdownguide.org/basic-syntax/#

I have a lengthy text saved in a string and I am looking to swap out certain words in the text with a highlighted version or a markdown link that directs to a glossary page explaining those specific words. The words needing replacement are contained within ...

Manipulating objects with ease in JavaScript

function abc(req, res, next) { let imageName = req.body.name; const obj = { imageName: { status: true, url: "abc" } } In the function above, there is a variable named 'imageName'. The goal is to use the value obtained i ...

Utilize React to generate HTML content and send it as the email body through Node.js

I am currently working on a react application that consists of two main pages - AddStatus and ViewStatus. Both of these are implemented as react components. My current task involves sending out an email daily at a specific time, containing the details dis ...

Unveiling Insights from a JSON File: Data Extraction

I have a JSON file named pio2.json that contains the following data: { "controles":[{ "chart":[{ "type":"columns", "title":"Pollitos" }], "datos":[{"key":"Math","value":98}, {"key":"Physics" ...

Implementing alphabetical pagination in PHP

I am trying to implement alphabetical pagination in php, but I am facing a problem. When I click on any alphabet, the selected alphabet shows up in the address bar, however, the data starting from the selected alphabet is not displayed. Here are my databa ...

A more detailed explanation of Angular's dot notation

I came across a solution for polling data using AngularJS here on stackoverflow. In this particular solution (shown below), a javascript object is used to return the response (data.response). I tried replacing the data object with a simple javascript arra ...

Tips for accessing elements other than the root element using this.$el

Within my template, the structure is as follows: <div v-show="showContent" class="content-block-body"> <div class="slider-pro"> <div class="sp-slides"> <slide v-for="block in subItems" ...

I'm confused, I installed the module but it's still showing an error message saying it can

I've been working on coding a discord music bot, and here is the code I have so far: const config = require('config.json') const Discord = require('discord.js'); const ffmpeg = require('ffmpeg-extra') const client = new ...

Creating a method for a Discord Bot to communicate through a Webhook (loop)

I am looking to enhance my bot's functionality by implementing a webhook triggered by a specific command. Once activated, the webhook should send a message at regular intervals. The idea is to obtain the token and ID of the created webhook, and then ...

Accordion in Bootstrap 5.3 behaving independently of data-bs-parent

I am currently working on designing an accordion feature where the headers are displayed in a column on the left side, and when expanded, the content appears in a column on the right side. Everything is working perfectly except for the fact that I have t ...

Determining if a swf file has loaded using JavaScript and swfobject

Here is the code snippet I am working with: <head> # load js <script> function graph() { swfobject.embedSWF( "open-flash-chart.swf", "chart", "400", "180", "9.0.0", "expressInstall.swf", {"data-file":"{% url moni ...

Issues with javascript and php carousel functionality not performing correctly

I am currently in the process of creating a slideshow/carousel for a website. Recently, I implemented a PHP for-loop to iterate through a folder of images, allowing me to use the slideshow with an unspecified number of images. However, after making this ch ...