A guide on integrating array map with a v-for loop in Vue

Struggling to understand how to implement a loop within another loop in Vue? This task might seem simple with React, but Vue presents its own challenges when it comes to using loops with arrays in templates/JSX.

The input data follows a specific format from the server. However, the code snippet provided below is currently not functional due to syntax errors.

Could you assist me in resolving these errors? It would greatly aid my comprehension of correctly applying nested loops in Vue templates...

const timeStamp = moment(new Date());
var app = new Vue({
  el: "#app",
  template: "#app-template",
  data: {
    symbols: [
      {
        id: 1,
        name: "EURUSD",
        candles: [
          {
            timeStamp: timeStamp.subtract(1, "days").format("YYYY-MM-DD"), // Yesterday
            open: 1.1,
            close: 1.2,
            high: 1.3,
            low: 1.0,
          },
          {
            timeStamp: timeStamp.format("YYYY-MM-DD"), // Today
            open: 1.2,
            close: 1.5,
            high: 1.6,
            low: 1.2,
          }
        ]
      },
      {
        id: 2,
        name: "USDRUB",
        history: [
          {
            timeStamp: timeStamp.subtract(1, "days").format("YYYY-MM-DD"), // Yesterday
            open: 75,
            close: 76,
            high: 77,
            low: 73,
          },
          {
            timeStamp: timeStamp.subtract(1, "days").format("YYYY-MM-DD"), // Today
            open: 76,
            close: 77,
            high: 79,
            low: 75,
          }
        ]
      }
    ]
  }
});
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script type="text/x-template" id="app-template">
  <table>
    <thead>
      <tr>
        <th>Symbol</th>
        <th>Change</th>
        <th>Time stamp</th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="(symbol, index) in symbols" :key="index">
        {
          symbol.candles.map(candle => {
            const { name } = symbol
            const { open } = candle.history[0]
            const { close, timeStamp } = candle.history[1]
            const change = Number.parseFloat((100 / (open / (close - open)))).toFixed(2)

            return (
              <td>{{ name }}</td>
              <td>{{ change }} %</td>
              <td>{{ timeStamp }}</td>
            )
          })
        }
      </tr>
    </tbody>
  </tabel>
</script>

Answer №1

Make sure to close your </table> tag properly, as you currently have a typo with </tabel>.

Consider using this approach for better efficiency:

    <tr v-for="(symbol, index) in symbols" :key="index">
      <template v-for="candle in symbol.candles">
        <td>{{ symbol.name }}</td>
        <td>{{ getChange(candle) }} %</td>
        <td>{{ candle.history[1].timeStamp }}</td>
      </template>
    </tr>

    ...

    methods: {
        getChange(candle) {
            const { open } = candle.history[0];
            const { close } = candle.history[1];
            return Number.parseFloat((100 / (open / (close - open)))).toFixed(2);
        }
    }

Using the <template> tag allows you to repeat code without adding unnecessary parent tags around it, as it does not render as HTML.

Moving logic outside of templates into methods is recommended due to Vue's limitation of one expression per data binding (source: https://v2.vuejs.org/v2/guide/syntax.html#Using-JavaScript-Expressions).

Answer №2

Appreciate your responses, I've updated the code in the snippet based on your suggestions. It's now functioning correctly. The key takeaway for me was understanding that the Vue <template> component is similar to React's <Fragment>.

document.addEventListener('DOMContentLoaded', function() {
    const timeStamp = moment(new Date());
    var app = new Vue({
        el: "#app",
        template: "#app-template",
        data: {
            symbols: [
                {
                    id: 1,
                    name: "EURUSD",
                    candles: [
                        {
                            timeStamp: timeStamp
                                .subtract(1, "days")
                                .format("YYYY-MM-DD"), // Yesterday
                            open: 1.1,
                            close: 1.2,
                            high: 1.3,
                            low: 1.0,
                        },
                        {
                            timeStamp: timeStamp.format("YYYY-MM-DD"),
                            open: 1.2,
                            close: 1.5,
                            high: 1.6,
                            low: 1.2,
                        },
                    ],
                },
                {
                    id: 1,
                    name: "USDRUB",
                    candles: [
                        {
                            timeStamp: timeStamp
                                .subtract(1, "days")
                                .format("YYYY-MM-DD"),
                            open: 75,
                            close: 76,
                            high: 77,
                            low: 73,
                        },
                        {
                            timeStamp: timeStamp.format("YYYY-MM-DD"),
                            open: 76,
                            close: 77,
                            high: 79,
                            low: 75,
                        },
                    ],
                },
            ],
        },
        methods: {
            moment: moment,
            getChange(candle) {
                const { open, close } = candle;
                return Number.parseFloat((100 / (open / (close - open)))).toFixed(2);
            }
        }
    });
});
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script type="text/x-template" id="app-template">
    <table>
        <thead>
            <tr>
                <th>Symbol</th>
                <th>Change</th>
                <th>Time stamp</th>
            </tr>
        </thead>
        <tbody>
            <template v-for="symbol in symbols">
                <tr v-for="(candle, index) in symbol.candles" :key="symbol.name + '-' + index">
                    <td>{{ symbol.name }}</td>
                    <td>{{ getChange(candle) }} %</td>
                    <td>{{ moment(candle.timeStamp).format("YYYY-MM-DD") }}</td>
                </tr>
            </template>
        </tbody>
    </table>
</script>
<div id="app"></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 steps can I take to troubleshoot a non-functional button in a Bootstrap 5 Modal?

I have a Django based web site that utilizes Bootstrap 5 for styling. Among the data presented on the site is a table with a notes column containing lengthy text. To enhance readability and keep the table compact, I attempted to integrate the Bootstrap Mod ...

Choose an option removed upon clicking

I need to remove the option with a value of 0 when the user selects from the dropdown list. Choose: <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <form:select id="CONTEXTE" path="CONTEXTE" onclick="go()" class="s ...

Struggling with obtaining react-modal in my React Component

Greetings to all React developers out there, especially the newbies like me. I am currently facing an issue with implementing react-modal in my React Component based on this example here. Unfortunately, I have encountered several errors that are proving di ...

Leveraging the sibling combinator for altering the class of a sibling SVG element with the assistance of Material

I have created an SVG picture that I am trying to animate. Behind the elements I want to animate on mouse hover, I have added transparent rectangles. The hover effect works well on these elements as the cursor changes to pointer. However, when I attempt t ...

Removing a Div with Dynamic Parameters

I'm struggling to implement a feature in my form that allows the user to add multiple entries, but I'm having trouble with the removal aspect. Here is the JavaScript code: var i = 1; var divContent = document.getElementById ...

Accessing object properties in the data of a Vue component

Recently delving into Vue, I've run into a bit of confusion. My app connects to a JSON Api using usePage(). The usePage() function allows me to utilize the "page" object within the <template> tag like so: <p>This product costs {{page.pric ...

Awaiting Node.js/Mongoose to patiently loop through asynchronous tasks

I have a question that might be quite basic for some. I am working with an array in my mongodb database and need to query/find multiple elements from it. My goal is to set an error variable to true if at least one element passes an if-statement. However, ...

"Slow loading times experienced with Nextjs Image component when integrated with a map

Why do the images load slowly on localhost when using map, but quickly when not using it? I've tried various props with the Image component, but none seem to solve this issue. However, if I refresh the page after all images have rendered once, they ...

What are the steps to integrate mp3 music into my web application?

Does anyone have experience implementing auto-resume mp3 music on a web application so that the music continues to play even when the user changes pages? I would like the music to seamlessly play as the user navigates through my web application. Can someo ...

Arranging data structures in JavaScript: Associative arrays

I'm facing a major issue. My task is to organize an array structured like this: '0' ... '0' ... 'id' => "XXXXX" 'from' ... 'name' => "XXXX" ...

Tips for solving issues with dependencies in React applications

After running "npm install," I encountered the following errors in the console: elena@elena-dev:~/PROYECTO FINAL CTD/grupo-12/frontend/proyecto-integrador$ npm install npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While reso ...

Querying and Retrieving a List of Nested Documents in MongoDB

I have multiple solutions, each of which may contain various projects. To represent this relationship, I opted for embedding the projects within the solution document. For example: [{ _id: "1", solutionTitle: "Some Sample Solution", p ...

What is the method by which jQuery achieves synchronous behavior in its $.ajax function?

I previously asked a similar question on Stack Overflow, but I wanted to approach it from a different angle to get more feedback. So far, I haven't found a solution that works for me. I am trying to make XCode execute a JavaScript command and receive ...

Is it possible to verify if each value satisfies a condition within a Javascript function?

I am currently working on a project using Vue.js and Laravel where I have a data list named "questions." My goal is to iterate through this list and check if the answer value for each question is not null. If any question has a null answer, I want to preve ...

Tips for adjusting the alignment of the Vuetify component "VDatePicker" based on the position of its parent component on the screen

Currently, I am utilizing the VMenu component from Vuetify which contains another Vuetify component called VDatePicker. The issue arises when clicking on a text field triggers the appearance of the calendar (VDatePicker). Normally, the VDatePicker componen ...

Tips for downloading a file using a Django function triggered by JavaScript instead of redirecting to the URL

Managing a page with multiple buttons that trigger various functions, such as sending an SMS (via API), emailing a file, or downloading a PDF. The button actions are powered by Ajax requests through JavaScript instead of using forms. I initially used Java ...

Can one recover a Javascript file from a server?

In Python, I am able to extract Javascript code from an HTML file using the code snippet below. import urllib2, jsbeautifier from bs4 import BeautifulSoup f = urllib2.urlopen("http://www.google.com.ph/") soup = BeautifulSoup(f, "lxml") script_raw = str( ...

Performing a PHP Curl request and an ajax query to an ASP.NET page

I am attempting to send an ajax query to an ASP.NET page. Here is the algorithm I am following: 1. There is a form on my webpage; 2. When the user fills in all the fields, they click the submit button; 3. Upon clicking the submit button, JavaScript sends ...

Tips for managing the onblur event using selenium automation framework

I want to trigger an onblur event when I click away using JavaScript. I tried the following code: ((JavascriptExecutor)getDriverProvider().executeScript("document.getElementByXpath('xpath here').onblur();"); However, it doesn't seem to wo ...

Struggling to eliminate the scrollbar on a Material UI Dialog

I have a modal window that includes a keyboard, but I'm encountering some issues. Despite adding overflow:'hidden' as inline CSS, the scrollbar refuses to disappear. Furthermore, even when utilizing container-full padding-0 in Bootstrap, th ...