Объединение 3-х рез.данных vue.js

#vue.js

#vue.js

Вопрос:

Я хочу объединить три res.data (carsIn,PositionUsed, позиция), эти res.data я получаю с помощью axios.get carsIn(идентификатор, имя пользователя, адрес пользователя, телефон пользователя, пластина) PositionUsed(id_pos, id_car, дата ввода) position (id_pos, имя пользователя) Я пробовал это решение, но мне нужно обновить 3 раза, чтобы получить данные в объединенном массиве, есть ли какое-либо решение? Я хочу получить mergedd (имя пользователя, адрес пользователя, телефон пользователя, номер, дата ввода, имя)

 export default {
    name: "Courses",
    data() {
        return {
            carsIn: [],
            PositionUsed:[],
            merged:[],
            positions:[],
            mergedd:[],
            message: "",
            INSTRUCTOR: "in28minutes"
        };
    },
    computed: {
        currentUser() {
          return this.$store.state.auth.user;
        }
    },
    mounted() {
        if (!this.currentUser) {
          this.$router.push('/login');
        }
    },
    methods: {
        refreshCourses() {
            clientService.retrieveAllCarsIn(this.INSTRUCTOR)
            .then((res) => {
                this.carsIn= res.data;
            });
            clientService.retrieveAllPositionOcp(this.INSTRUCTOR)
            .then((res) => {
                this.PositionUsed= res.data;
                for(let i=0; i<this.carsIn.length; i  ) {
                    this.merged.push({
                        ...this.carsIn[i], 
                        ...(this.PositionUsed.find((itmInner) => 
itmInner.id_car === this.carsIn[i].plate))}
                    );
                }
            });
            clientService.retrieveAllPositions(this.INSTRUCTOR)
            .then((res) => {
                this.positions = res.data;
                for(let i=0; i<this.merged.length; i  ) {
                    this.mergedd.push({
                        ...this.merged[i], 
                        ...(this.positions.find((itmInner) => itmInner.id_pos 
=== this.merged[i].id_pos))}
                    );
                }
            });

        }
    },
    created() {
        this.refreshCourses();

    }
}  

Ответ №1:

Это лучшее решение, но оно будет работать, только если clientService.retrieveAllCarsIn , clientService.retrieveAllPositionOcp и clientService.retrieveAllPositions являются обещаниями

 refreshCourses() {
  Promise.all([clientService.retrieveAllCarsIn(this.INSTRUCTOR) ,  clientService.retrieveAllPositionOcp(this.INSTRUCTOR)] , clientService.retrieveAllPositions(this.INSTRUCTOR)).then((response) =>{
    this.carsIn= response[0].data;
    this.PositionUsed= response[1].data;
    this.positions =  response[2].data;
  }).catch((err) =>{
    //error handler
  }).finally(() =>{
    
  })
}
  

Комментарии:

1. что мне добавить .finally(()=>{ //здесь })? и где я нахожу выходные объединенные данные?

2. у вас есть carsIn PositionUsed и объекты positions, и вы можете объединять их по своему усмотрению. блок finally() будет запущен после выполнения всех обещаний.

Ответ №2:

Похоже, вы можете переписать свою функцию примерно так:

 refreshCourses() {
    // Get data for all 3 requests at the same time
    const [courses, pos, positions] = Promise.all([clientService.retrieveAllCarsIn(this.INSTRUCTOR), clientService.retrieveAllPositionOcp(this.INSTRUCTOR), clientService.retrieveAllPositions(this.INSTRUCTOR)]);
    // Now iterate over courses
    this.mergedd = courses.map(({
        id,
        namecourse,
        desc,
        plate
    }) => {
        // Get date from pos array
        const {
            date,
            id_position
        } = pos.find(p => p.id_car === plate); // Or p.id_course === id
        // Get nameposition from positions array
        const {
            nameposition
        } = positions.find(p => p.id === id_position);
        const out = {
            id,
            namecourse,
            desc,
            date,
            nameposition
        }
    });
}
  

Комментарии:

1. я ошибся в данных, прошу прощения, вы можете обновить свое решение?