[Vuejs]-Value from for each loop doesn't get returned

3👍

Your filter callback is not proper for what you want to achieve.
Try this one below :

filterTrainStations: function() {

    // Direction where the train has to go to.
    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});
    });
)}

Let me know if this helps

EDIT: Made an edit to include your code as well, so that you can easier see how to use it!

4👍

Why does the value the value u doesn’t get returned?

Because the return statement just returns out of the function passed to forEach it does not return from the outer filter method. You should instead use find and return the result:

filterTrainStations: function() {

    // Direction where the train has to go to.
    const city = this.city.mediumName; // New York

    return this.response.payload.departures.filter(function(u) {
        // Only return the trains which go to the right direction. 
        if(u.direction === city) {
            return u;
        }   

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

But this raises another issue – the lines of code are themselves inside a filter where you should be returning true or false depending on if you want that item included or not in the result. Without more info it is hard to reconcile the actual problem you’re having. However, returning anything truthy will result in that departures item being included in the result.

Personally, I would do it as MKougiouris answer suggests, as it is much clearer.

👤Jamiec

Leave a comment