Loop through each instance of a data record in a JSON document using Vue's v-for directive

I am currently working on a project that involves extracting data from a website that monitors traffic jams and maintenance work. My goal is to specifically retrieve information about traffic jams and display them individually.

The code I am using utilizes Axios to fetch data from a fixed URL: . I have successfully managed to extract relevant details from this file:

{{roadEntries[0].events.trafficJams[0].from}} => Starting point of the jam
{{roadEntries[0].events.trafficJams[0].to}} => End point of the jam
export default {
        name: "Melding",
        data() {
            return {
                datum: {},
                roads: {},
                informations: {},
                roadEntries: {},
            }
        },
        mounted() {
            const axios = require('axios');
            const api = 'https://www.anwb.nl/feeds/gethf';

            // Making a request for specific data
            axios.get(api).then((response) => {
                this.informations = response.data;
                this.datum = response.data.dateTime;
                this.roadEntries = response.data.roadEntries;
                this.roads = response.data.roadEntries;
            })
        }
    }

Template:

<div>
        <p>{{ datum }}</p>
        <hr>
        {{roadEntries[0].road}}
        {{roadEntries[0].events.trafficJams[0].from}}
        {{roadEntries[0].events.trafficJams[0].to}}
    </div>

While I succeeded in storing the "from" data(), attempting to loop through it resulted in displaying individual letters rather than complete words.

Additionally, due to the presence of arrays within the information file, processing the data has proven challenging. Extracting the "datum" was straightforward as it consisted of just one static string.

I would greatly appreciate some guidance on how to effectively iterate through each entry in the file and showcase them in the template.

Answer №1

In order to showcase the traffic jams, you will need two loops. The first loop iterates through the roadEntries array, while the second inner loop goes through the trafficJams array for each road.

If you want to delve deeper into how loops are utilized in vue.js, I recommend reading the v-for documentation.

For cases like these, a computed property proves to be extremely useful in filtering out roads that have not experienced any traffic jams.

new Vue({
  el: '#app',
  data() {
    return {
      datum: '',
      roadEntries: [],
    }
  },
  computed: {
    roadEntriesWithTrafficJams() {
        return this.roadEntries.filter(roadEntry => roadEntry.events != null && roadEntry.events.trafficJams != null && roadEntry.events.trafficJams.length > 0);
    }
  },
  mounted() {
    const api = 'https://www.anwb.nl/feeds/gethf';

    // Make a request for a user with a given ID
    axios.get(api).then((response) => {
      this.datum = response.data.dateTime;
      this.roadEntries = response.data.roadEntries;
    })
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<div id="app">
  <h3>
   Date time : {{ datum }}
  </h3>
  <div v-for="roadEntry in roadEntriesWithTrafficJams">
    <h4>
    {{ roadEntry.road }}
    </h4>
    <div v-for="trafficJam in roadEntry.events.trafficJams">
       {{ trafficJam.from }} - {{ trafficJam.to }}
    </div>
  </div>
</div>

Answer №2

Although my solution may not encompass the entire Vue implementation, I have concentrated on demonstrating how you can extract necessary data from an API response and store it in an array for looping using v-for:

// Here are some variables to consider adding to your Vue data()
let date = '';
const trafficJams = [];

axios.get('https://www.anwb.nl/feeds/gethf')
.then((resp) => {
    date = resp.data.dateTime;
    const roadEntries = resp.data.roadEntries;
    // Iterate through all roadEntries
    roadEntries.forEach(entry => {
        // Extract the trafficJams array to a variable for better readability
        const jams = entry.events.trafficJams;
        // Check if there are any jams on the given road (entry)
        if (jams.length > 0) {
            // Loop through all traffic jams and add the required data to your variable
            jams.forEach(jam => {
                trafficJams.push({
                    road: entry.road,
                    from: jam.from,
                    to: jam.to
                });
            });
        }
    });
    // You now have "road", "from", and "to" data for all traffic jams
    console.log(trafficJams);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.min.js"></script>

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

Output each element of an array in Vuejs2 with a line break between each

I am currently working with vuejs2 and have a select tag where a person is selected, with their address properties directly bound to the element. I need to display the address of the selected person. I attempted to use an array in order to print out the el ...

When I press the right arrow key, the cursor vanishes into thin air

A content editable div contains HTML elements such as spans and plain text. View fiddle .ing-tag_0{ color:white; background-color: blue; } <div value="" id="step_input_0" name="step" placeholder="Tell us about step 1" class="input stepbox step ...

An easy guide to rerouting a 404 path back to the Home page using Vue Router in Vue.js 3

Hello amazing community! I'm facing a small challenge with Vue.js 3. I am having trouble setting up a redirect for any unknown route to "/" in the router. const routes = [ { path: "/", name: "Home", component: Home, }, { path: "* ...

Highlighting a Table Column with a Radio Button

I am struggling with controlling the highlight of a table using only radio buttons. When I try to change the selector to input:radio, it doesn't work as expected. It seems to only work with the selector provided in my code snippet. $("th").on("clic ...

Steps to handle the change event of a p:inputText element

In my current setup, I am utilizing p:inputText and have the need to trigger a javascript function that will update the searchField in the backend bean. <p:inputText required="true" placeholder="#{cc.attrs.searchTip}" value="#{cc.attrs.queryProperty}" ...

What is the reason behind my titles being triple the length they should be?

Here is my personal website The titles are appropriately set for the About College section Note: Utilizing Purl library for this purpose var seg2 = ''; if (url.segment(2) == 'college-life') seg2 = "College Life"; else if (url.seg ...

Exploring the functionality of the readline module using a simulated command-line

I am currently working on developing a unit test for a module that utilizes the "readline" functionality to interpret standard input and provide standard output. Module: #!/usr/bin/env node const args = process.argv.slice(2) var readline = require(' ...

What is the process for securing a photo to a canvas?

I have included <input type='file' id="image"> in my HTML code. How can I display the uploaded image on my canvas using p5.js? What is the best way to add an event listener to this action and transfer the uploaded file onto the ca ...

change the return value to NaN instead of a number

Hey there, I have something similar to this: var abc1 = 1846; var abc2 = 1649; var abc3 = 174; var abc4 = 27; if(message.toLowerCase() == ('!xyz')) { client.say(channel, `abc1` +`(${+ abc1.toLocaleString()})` +` | abc2 `+`(${+ abc2.toLocaleStri ...

Managing a prolonged press event in a React web application

Hello everyone! I am currently using React along with the Material UI library. I have a requirement to handle click events and long-press events separately. I suspect that the issue might be related to asynchronous state setting, but as of now, I am unsu ...

The users in my system are definitely present, however, I am getting an error that

Whenever I attempt to retrieve all the post.user.name, an error is displayed stating Cannot read properties of undefined (reading 'name') I simply want to display all the users in my node Even though user is not null, when I write post.user, i ...

Using JavaScript to Filter Through Numerous Values Based on Different Attributes

My goal is to efficiently filter multiple attributes with multiple values 'arr' represents a list of all products, and 'f_...' indicates the attribute such as color or type. 'namet' denotes the selected attribute by the user ...

Error: JavaScript object array failing to import properly

In my code, I have an array of objects named trace which is defined as follows: export const trace: IStackTrace[] = [ { ordered_globals: ["c"], stdout: "", func_name: "<module>", stack_to_render: [], globals: { c: ["REF" ...

Vue and Vuex retrieve state data from the server in a single request

When loading the History view, data is fetched from the backend server using a Vuex action called in the created() lifecycle hook. This data is then passed to the history table through a computed function named history(), which accesses the history module ...

What could be the issue with my code? (Threejs spotlight shadow)

I recently created a Three.js scene featuring two cubes on a plane. The spotLight I placed in the top-left corner is intended to look at the coordinates 50, 0, -50. However, I noticed that the shadows appear odd and the light does not seem to be focusing ...

Incorporating Javascript into HTML

I have developed a script to randomly change the size of an element, but I am struggling to understand how to incorporate it using HTML or iframe code for randomization. <script type="text/javascript"> var banner1 = ["728", "90"]; var banne ...

What is the most effective method for dividing a string in TypeScript?

Here is the scenario: receiving a string input that looks like Input text: string = "today lunch 200 #hotelname" Output subject: "today lunch" price: 200 tag: #hotelname My initial solution looks like this: text: string = "today lunch 200 #hotelname" ...

Implementing the MVC pattern in the app.js file for a Node.js and Express web application

After completing several tutorials on nodejs, mongodb, and express, I have gained a solid understanding of the basics such as: The main controller file being app.js. Third party modules stored in their designated node_modules directory. Template files pl ...

Using PHP, jQuery, and HTML to submit a form and insert data into MySQL, all while

I am facing an issue with my PHP intranet site, which includes an HTML form with 2 input fields. My goal is to take the user's input from the form and insert it into a MySQL database without redirecting the user to another page. I have a separate PHP ...

Is it possible to use vanilla JavaScript scroll event with AngularJS framework?

I am attempting to track the window offset from the top of the document, but I am facing issues with jQuery scroll functionality. Can a vanilla JavaScript scroll event listener be used effectively within an Angular environment? app.directive('owlCaro ...