Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

121
Visualizações
How can I synchronize the ids in the data using vue js and reach the name corresponding to the id?

I have two different endpoints in the project I am working on. One of these endpoints (categories) gives me the category name and id value, and the other (products) gives me only the category id value. I want to extract the id values from both endpoints and add the name corresponding to the id value from the category part of the fields with equal id values to the product part.

I made synchronizations using the for loop below and then I synced it to the Category name of the product, but there was too much code and it doesn't work stably. By stable I mean the data sometimes comes and sometimes it doesn't, it doesn't give any error either. How do you think I can write shorter and more stable?

data:

    products: {
  items: [{ categoryName: '' }],

},

cretated(){

 fetch('example/products')
  .then((response) => {
    return response.json();
  })
  .then((data) => {
    this.products = data;
  });

fetch('example/categories')
  .then((response) => {
    return response.json();
  })
  .then((data) => {
    this.categories = data;
    this.pushNametoCategoryNames();
  });
}

methods() {       
pushNametoCategoryNames() {
      for (let i = 0; i < this.products.items.length; i++) {
        for (let j = 0; j < this.categories.length; j++) {
          console.log(this.products);
          console.log(this.categories[j]);
          if (this.products.items[i].categoryId == this.categories[j].id) {
            this.products.items[i].categoryName = this.categories[j].name;
          }
        }
      }
    },
    }
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can never guarantee that this.pushNametoCategoryNames() will run after both of the fetch calls, unless you call the second fetch from the then of first fetch, or use async-await.

Approach 1

   fetch('example/products')
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        this.products = data;
         fetch('example/categories')
         .then((response) => {
            return response.json();
          })
         .then((data) => {
         this.categories = data;
            this.pushNametoCategoryNames();
         });
      });

Approach 2

async cretated(){
   this.products = await (await fetch('example/products')).json();
   this.categories = await (await fetch('example/categories')).json();
   this.pushNametoCategoryNames();
}

Approach 3 (Promise.all)

cretated(){
   Promise.all([fetch('example/products'), fetch('example/categories')]).then(values => {
      Promise.all([values[0].json(), values[1].json()]).then(data => {
           this.products = data[0];
           this.categories = data[1];
           this.pushNametoCategoryNames();
      });
   });
   this.pushNametoCategoryNames();
}
about 4 years ago · Juan Pablo Isaza Relatório

0

You can use map and wait for responses :

new Vue({
  el: "#demo",
  data() {
    return {
      products: [],
      categories: []
    }
  },
  async mounted(){
    await fetch('https://jsonplaceholder.typicode.com/posts/')
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        this.products = data;
      });
    await fetch('https://jsonplaceholder.typicode.com/users/')
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        this.categories = data;
      });
    this.pushNametoCategoryNames();
  },
  methods: {       
    pushNametoCategoryNames() {
      this.products = this.products.map(p => {
        const cat = this.categories.find(c => p.userId === c.id).username
        cat ? p.CATNAME = cat : p.CATNAME = 'EMPTY'
        return { ...p }
      })
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  {{products}}
</div>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda