K
K
kmv-dev2021-04-04 13:17:25
Vue.js
kmv-dev, 2021-04-04 13:17:25

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>


in db.json created a two-dimensional array with data. In the second array of 2, I added a key with a value that occurs in the first array in order to compare them later and display only the data that matched.
Tell me how to display only the car.name that passed the check stations.name === cars.address?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-04-04
@kmv-dev

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 question

Ask a Question

731 491 924 answers to any question