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

What are some ways to personalize a scrollbar?

I am looking to customize the scrollbar within a div. I attempted to modify it using the code below, but I encountered difficulties when trying to change the scroll buttons and did not achieve my desired outcome. Additionally, this customization did not wo ...

Tallying the number of words delimited by a comma

Here is how my counter function is structured: function count() { var value = ids.val(); return (value == '') ? 0 : value.replace(/\s,?|,$/g, '').split(',').length; } After checking the returned value, data is ...

Troubleshooting a jQuery filter function selector issue

Here's a function I've created: $.fn.filterByClass = function(cls) { var o = $(this); return o.filter(function() { if ($(this).attr("class") == cls) { return $(this); } }); }; Let's say we have multiple fo ...

p5.js experiencing issue: Uncaught TypeError - Unable to access property 'transpose3x3' due to null value

I have a simple website built with Flask where I am running several p5.js sketch animations, and everything is working smoothly. However, when I try to add a new sketch that utilizes WEBGL, I encounter the following error: Uncaught TypeError: Cannot read p ...

Guide on sharing a Vue project with other devices within a network

I'm a complete beginner when it comes to vue.js. After working on a few small projects, I want to make sure I understand how to share a vue project with others at this stage. Typically, I know that running 'npm run serve' in my project dir ...

Postman: Iterating through requests with various input data sets to dynamically generate the request body

I am facing a challenge with my login API request that requires 3 parameters (userName, password, and remember) in the request body. Out of these parameters, userName and password are mandatory, while remember is optional. The input data is being pulled fr ...

Problem with full-page navigation sliding in and fading in and out

Upon the user's click on <a href="#slide-nav" class="slide-nav-trigger">, a full-page navigation smoothly slides into view. This animation is triggered by CSS and uses jQuery for event delegation. The Dilemma Instead of abruptly turning on and ...

Override existing Keywords (change false to true)

Are there any ways to overwrite reserved words? It's not something I would typically consider, but it has sparked my curiosity. Is it feasible to set false = true in JavaScript? I've come across instances on different websites where individuals ...

Transforming an Excel document into JSON format: inspection of JSON code structure

Looking to transform Excel data into JSON format, but unsure if the current structure will be ideal for processing with D3.js. Planning to incorporate this JSON file within D3.js for visualization purposes. Here's a snippet of the Excel file: In the ...

How to retrieve specific items from an array contained within an array of objects using Express.js and MongoDB

Within the users array, there is an array of friends. I am looking to retrieve all friends of a specific user based on their email where the approved field is set to true. In my Node.js application, I have defined a user schema in MongoDB: const UserSchem ...

The Angular7 counterpart of the C# attribute decorator

I'm working with an API method that has an Authorize attribute to verify permissions. [Authorize(ReadIndexes)] public async Task<IActionResult> GetIndexes () { ... } Is there a similar way in Angular to implement permission checks so the API ...

The Antd Tooltip becomes unresponsive when a component is clicked and moved

Having an issue with a button that has an Antd tooltip, here is the setup: <Tooltip title="Some text"> <button onClick={openNotes}><Icon icon="notes" /></button> </Tooltip> Upon clicking the button, the ...

Step-by-step guide to start an AngularJs application using TypeScript

I have developed an AngularJS App using TypeScript The main app where I initialize the App: module MainApp { export class App { public static Module : ng.IModule = angular.module("mainApp", []) } } And my controller: module MainApp { exp ...

Guide for dynamically populating Jqgrid Dropdown depending on another dropdown's data选择如何根

On my screen, I have two dropdowns. One is a standard Razor dropdown and the other is a Jqgrid dropdown. The code for the Razor dropdown looks like this: <div class="col-md-4"> <label for="" class="control-label">Loan Currency</ ...

Utilizing AngularJS element.find results in modifications to my objects

Encountering an issue with angularJS when trying to locate elements. It appears that the objects are being altered when using element.find('type').attr('id' ,someid); Here are some additional details: The directive is only used in on ...

Pedaling back and forth along a sequence

Is there a way to implement forward and backward buttons for a clickable list without using arrays, as the list will be expanding over time? I have already achieved changing color of the listed items to red, but need a solution to navigate through the list ...

Incorporate style elements dynamically using an array in Vue

My progress bar's width and color are determined by data from an array. The color of the bar changes based on the value of the data - grey if the progress is 0, blue if it's more than 0, and green if it's 100. <div class="card-item" v-fo ...

Finding the best way to transfer text between DIV elements?

I have a dilemma involving two DIV elements positioned absolutely on the sides of an HTML page, much like this EXAMPLE: <div class="left"> </div> <div class="right"> </div> These are styled using the following CSS: .left{ pos ...

One potential solution is sending a message to a user via a server using JavaScript on Node.js

Hey there, I've encountered a minor issue and would appreciate your help. Recently, I developed a weather program in NodeJs where users can search for the weather in their city. However, I'm facing a challenge with displaying the weather data to ...

Isn't AJAX all about the same origin policy?

Despite my confusion surrounding the same domain origin policy and jQuery AJAX, I have noticed that when I make a GET request to a URL using jQuery, I am able to successfully retrieve the results. This goes against what I understood about the restriction ...