The for each loop fails to return the value

In my Vue component, I have a conditional loop that iterates through train stations with 'New York' as the destination or on the route.

<tr v-for="departure in filterTrainStations" :key="departure.name">
            <td>{{ departure.product.categoryCode }}</td>
            <td>{{ departure.direction }}</td>
            <td>{{ getTimeFromDate(departure.actualDateTime) }}</td>
            <td>{{ departure.name }} </td>
        </tr>

My table using the loop currently displays trains heading to 'New York'. However, there are also trains going in another direction but passing through 'New York'. So, I need to account for those trains as well. Here's my computed function filterTrainStations:

filterTrainStations: function() {

    // Desired city for the train to reach.
    const city = this.city.mediumName; // New York

    return this.response.payload.departures.filter(function(u) {
        // Return trains headed to the specified city.
        if(u.direction === city) {
            return u;
        }

        // Check for trains passing through the desired city.
        u.routeStations.forEach(function (arrayItem) {
            if(arrayItem.mediumName === city) {
                console.log(u);
                return u;
            }                    
        })
    }
)},

The value returned from the forEach function isn't being captured, even though it shows the correct information when logged.

My question is:

Why doesn't the value of u get returned?

The API response containing the departure information looks like this:

response: {
          "links": {},
            "payload": {
                "source": "PPV",
                "departures": [
                    {
                        "direction": "Weert",
                        "name": "NS  5249",
                        "plannedDateTime": "2019-10-10T15:08:00+0200",
                        "plannedTimeZoneOffset": 120,
                        "actualDateTime": "2019-10-10T15:08:00+0200",
                        "actualTimeZoneOffset": 120,
                        "plannedTrack": "1",
                        "product": {
                            "number": "5249",
                            "categoryCode": "SPR",
                            "shortCategoryName": "NS Sprinter",
                            "longCategoryName": "Sprinter",
                            "operatorCode": "NS",
                            "operatorName": "NS",
                            "type": "TRAIN"
                        },
                        "trainCategory": "SPR",
                        "cancelled": false,
                        "routeStations": [
                            {
                                "uicCode": "8400129",
                                "mediumName": "Boxtel"
                            },
                            {
                                "uicCode": "8400206",
                                "mediumName": "Eindhoven"
                            },
                            {
                                "uicCode": "8400245",
                                "mediumName": "Geldrop"
                            }
                        ],
                        "departureStatus": "INCOMING"
                    },
                ]
            },
            "meta": {}
          }

Answer №1

How come the value of variable u is not returned?

The reason is that when using the return statement within a function passed to forEach, it only exits out of that function and does not return from the outer filter method. To fix this issue, you should utilize the find method and return the desired result:

filterTrainStations: function() {

    // Specify the direction where the train needs to go.
    const city = this.city.mediumName; // New York

    return this.response.payload.departures.filter(function(u) {
        // Only include trains heading towards the specified direction. 
        if(u.direction === city) {
            return u;
        }   

        // Check for any trains with the desired city in their route.
        return u.routeStations.find(arrayItem => arrayItem.mediumName === city);
    }
)},

However, there is another problem here - the code lines are enclosed within a filter function where you should be returning true or false based on whether you want the item to be included in the final result. Without more information, it's difficult to pinpoint the exact issue you're facing. Nonetheless, any truthy return value will result in including that departures item in the result.

I personally prefer following the approach suggested by MKougiouris answer as it provides clearer guidance.

Answer №2

It seems like your current filter callback may not be suitable for your desired outcome. Consider trying the suggested code snippet below:

filterTrainStations: function() {

    // Specify the direction in which the train should travel.
    const city = this.city.mediumName; // New York

    return this.response.payload.departures.filter(function(u) {
        return u.direction == city || u.routeStations.some(function(rs){ rs.mediumName == city});
    });
)}

Please let me know if this solution works for you.

EDIT: I have also included your original code snippet for easier comparison and understanding of how to implement it!

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

Configuring the data source for an autocomplete feature in ReactJS Material UI

For one of my React components, I am utilizing the Material UI autocomplete feature. The data source is retrieved from the server asynchronously and has the following structure: const dataSource = [{ id: 001 firstName: 'fname', lastName: &apo ...

Obtaining Beverage Overall with Loop

I am currently using a function to calculate the total of each drink, with a total of 5 drinks: var totalEstimate = 0; var locoCost = 0; var blackCost = 0; function calcLoco() { totalEstimate -= locoCost; locoCost = docume ...

What is the process for sending a request to a static resource along with parameters?

I currently have a node.js restify server running, along with a folder containing static resources. const restify = require('restify') let server = restify.createServer() server.listen(8080, function () { console.log('%s listening at ...

Ways to avoid unintentional removal of contenteditable unordered lists in Internet Explorer 10

How can I create a contenteditable ul element on a webpage while avoiding the issue in Internet Explorer 10 where selecting all and deleting removes the ul element from the page? Is there a way to prevent this or detect when it happens in order to insert ...

Get the nearest offspring of the guardian

I have a main 'container' div with multiple subsections. Each subsection contains 1 or 2 sub-subsections. Let's say I have a variable that holds one of the subsections, specifically the 4th subsection. This is the structure:container > s ...

Failed attempt to perform Ajax requests for REST API data

I am currently working on developing an application that requires a login through a REST API to retrieve a session id. To achieve this, I have set up a button that triggers a JavaScript function for making an AJAX call to authenticate the user. The result ...

Using v-model with checkboxes in vue.js: A Step-by-Step Guide

How can I use a checkbox with a v-model in Vue2.js? <input type="checkbox" value="test" :checked="selected"/> I need the value of the checkbox to be test, and I also require two-way binding with the prop named selected, ...

Restrict Vue Router access to specific pages only

Once a user has logged in for the first time, they are directed to the CreateProfile page where they can enter their profile information. I want to restrict access to this page so that if the user manually types the URL into their browser (e.g. www.myproje ...

Attempting to iterate over the array of objects in order to discover a match

I am currently working with an object structure that resembles the one shown in the image linked below. My goal is to compare the inner object properties (such as massing type id) with existing IDs. If there is a match, I want to retrieve the name of that ...

Session Redirect Error in Express.js

Encountering an error consistently when running my code with the pseudocode provided below (Just to clarify, my code is built on the react-redux-universal-hot-example) Error: Can't set headers after they are sent. [2] at ServerResponse.OutgoingMe ...

Troubleshooting Vue Unit Tests: Issue with Setting Input Values

I am currently utilizing Vue with typescript and making an effort to perform a unit test on the input value for a login page. The issue lies in the fact that after setting the input value, it does not return as expected – instead, it comes back empty ("" ...

Utilizing an Array of objects in conjunction with $.when

I have a list of Ajax requests stored in an Array, and I need to wait for all of them to finish loading before processing the results. Here is the code snippet I am currently using: $.when( RequestArray ).done(function(){ this.processResu ...

Issue arises when isomorphic-dompurify is used alongside dompurify in Next.js 13 causing compatibility problems

I am currently facing a compatibility problem involving isomorphic-dompurify and dompurify in my Next.js 13 project. It appears that both libraries are incompatible due to their dependencies on canvas, and I am struggling to find a suitable alternative. M ...

I'm having trouble installing puppeteer

I tried running the command npm i --save-dev puppeteer to set up puppeteer for e2e testing. Unfortunately, an error occurred during installation: C:\Users\Mora\Desktop\JS\Testing>npm i --save-dev puppeteer > <a href="/cd ...

Once the Ionic platform is prepared, retrieve from the Angular factory

I have created a firebase Auth factory that looks like this: app.factory("Auth", ["$firebaseAuth", "FIREBASE_URL","$ionicPlatform", function($firebaseAuth, FIREBASE_URL, $ionicPlatform) { var auth = {}; $ionicPlatform.ready(function(){ ...

Building a collapsible toggle feature with an SVG icon using HTML and CSS

I am trying to swap a FontAwesome Icon with a Google Materials SVG Icon when a collapsible table button toggle is pressed (changing from a down arrow to an up arrow). I have been struggling to get the Google Material Icons code to work. How can I resolve t ...

Integrating XML API Requests Using HTML and JavaScript

When there is only one item in the XML document, I want to update my inner HTML with the result of an API call. I have managed to successfully make the API call work when there are multiple items in the XML document (thanks to W3). <!DOCTYPE html> ...

Error: Reference 'ref' is undefined in the 'no-undef' context. I am interested in experimenting with loading images from Firebase storage

While working with React, I encountered an issue when trying to fetch an image URL from Firebase Storage and display the image. The error 'ref' is not defined (no-undef) occurred. https://firebase.google.com/docs/storage/web/create-reference Th ...

When Index.html is hosted via Express, the component fails to render

Following a tutorial has led me to the end and I've made changes to my App.js as shown below: import React, { Component } from "react"; import "./App.css"; class App extends Component { render() { return ( <div> <p>lm ...

Can you explain the significance of the regular expression in a dojo configuration file named dj

As I was working on developing dojo application modules, I came across a regular expression in tutorials. var pathRegex = new RegExp(/\/[^\/]+$/); var locationPath = location.pathname.replace(pathRegex, ''); var dojoConfig = { asyn ...