Answer the question
In order to leave comments, you need to log in
How to filter v-for by comparing values from another array?
<template>
<div class="home" v-for="station of stations" :key="station.id" >
<h1>{{ station.name }}</h1>
<ul>
<li v-for="car of car_filter" :key="car.id">{{ car.name }}</li>
</ul>
</div>
</template>
<script>
const axios = require('axios');
export default {
name: 'Home',
data() {
return {
stations: [],
cars: []
}
},
mounted() {
Promise.all([
axios.get(`http://localhost:3000/stations`),
axios.get(`http://localhost:3000/cars`)
]).then(([stations, cars]) => {
this.stations = stations.data;
this.cars = cars.data;
});
},
computed: {
car_filter: function () {
return this.cars.filter( function () {
return this.stations.name === this.cars.address; ----- такая конструкция не работает
})
}
}
}
</script>
Answer the question
In order to leave comments, you need to log in
computed: {
stationsWithCars() {
return this.cars.reduce(
(acc, n) => (acc[n.address]?.cars.push(n), acc),
Object.fromEntries(this.stations.map(n => [ n.name, { station: n, cars: [] } ]))
);
},
},
<div v-for="{ station, cars } in stationsWithCars" :key="station.id">
<h1>{{ station.name }}</h1>
<ul>
<li v-for="car in cars" :key="car.id">{{ car.name }}</li>
</ul>
</div>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question