我的Vue组件中有一个条件for-loop
。我只想在以“纽约”为目的地,或“纽约”在途中的火车站中循环行驶。
<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>
这是我的for-loop
表。它目前向我显示了所有以“纽约”为方向的火车。但是也有其他方向的火车,但路线上有“纽约”标志。所以我也想检查一下。这是我计算的filerTrainStations
函数:
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.
u.routeStations.forEach(function (arrayItem) {
if(arrayItem.mediumName === city) {
console.log(u);
return u;
}
})
}
)},
应该从forEach
函数返回的值不返回任何内容,但是当我console.log
时,它向我显示了正确的信息。
我的问题是:
为什么未返回值
u
的值?
我从API那里获取出发信息的响应如下:
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": {}
}
答案 0 :(得分:4)
为什么不返回u的值?
由于return
语句只是从传递给forEach
的函数中返回,因此它不会从外部filter
方法中返回。您应该改用find
并返回结果:
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);
}
)},
但这会引发另一个问题-代码行本身位于filter
中,您应在其中返回true
或false
,具体取决于您是否希望将该项目包含在结果。没有更多信息,很难调和您遇到的实际问题。但是,返回 anything 真值将导致该departures
项目包含在结果中。
就个人而言,我会按照MKougiouris answer的建议进行操作,因为这要清楚得多。
答案 1 :(得分:3)
您的过滤器回调不适合您要实现的目标。 在下面试试这个:
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});
});
)}
让我知道这是否有帮助
编辑:进行编辑以同时包含您的代码,以便您可以更轻松地了解如何使用它!