Is there a way to link the IDs in the data with Vue.js to access the corresponding names?

In the project I'm currently working on, I have two endpoints that provide different information. The 'categories' endpoint supplies me with category names and their corresponding id values, while the 'products' endpoint only gives me the category id values. My goal is to match the id values from both endpoints and assign the respective category names to the products.

To achieve this, I initially attempted to synchronize the data using a nested loop structure, but it led to verbose and unstable code. The instability arises from the inconsistent retrieval of data, sometimes returning results and sometimes not, without any clear error indication. How can I optimize the code to be concise and more reliable?

data:

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

created(){

 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;
          }
        }
      }
    },
    }

Answer №1

There is no guaranteed way to ensure that this.pushNametoCategoryNames() will be executed after both fetch calls, unless the second fetch is called from the then of the first fetch, or using async-await.

Procedure 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();
         });
      });

Procedure 2

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

Procedure 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();
}

Answer №2

To retrieve data and map the responses, you can utilize the map function in Vue.js:

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.combineUserWithCategory();
  },
  methods: {       
    combineUserWithCategory() {
      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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can one update transitive dependencies to a specific newer version in npm to address CVE vulnerabilities?

Here are the packages that require upgrading. I attempted to update the version and signature of the packages listed in package-lock.json. However, whenever I run npm i after modifying package-lock.json, the changes made to package-lock.json disappear. ...

The error message "jsPDF is not defined in Laravel using Vuejs and bootstrap-table-vue"

I encountered an issue when attempting to export a Bootstrap table in Vue as a PDF format. The error message I received was: app.js:100649 Uncaught ReferenceError: jsPDF is not defined at jQuery.fn.init../node_modules/tableexport.jquery.plugin/tableEx ...

Using Laravel to send a model with a related Vue component

Currently, I am in the process of learning how to utilize Vue and Laravel. As a part of this learning journey, I am developing Vue components to replace certain sections of the blades. Within my application, I have a model named Sugerencia (suggest). Alon ...

Customize the behavior of jQuery cycle with an <a> tag

Can the jQuery cycle be accessed through a link in order to override the i variable? I've come across examples that can achieve this, but not in a scenario like this where the cycle() function is located within a variable: $(document).ready(function ...

Can a File Object be transmitted to an AWS Lambda function via API Gateway using JavaScript?

Can a JavaScript File Object be passed from a browser to AWS Lambda via API Gateway (ultimately to S3)? I am working with TypeScript and React. Environment Frontend TypeScript React AWS Amplify (for API module) Backend(AWS Lambda) Node.js Expecta ...

Customizing Cell Templates in Angular UI-Grid Based on Conditions

I am struggling to display a button in my ui-grid only when the field value is not an empty string. I attempted using the ng-if directive, but it is not functioning as expected. Below is the snippet from my grid options: { field: 'ReleaseStatus&apo ...

listening for events on nested classes

I am looking to dynamically toggle the class "collapsed" on each element with the class "category" when it is clicked. The issue arises when these "category" elements are nested within each other, causing the child elements to also trigger the class change ...

"Utilizing JSON.parse() to convert a string captured from a PythonShell back

Using PythonShell in Node to execute a Python script that generates a Python dict, such as: { "playedStatus": game['playedStatus'].encode('ascii'), "awayTeamAbb": game['awayTeamAbb'].encode('ascii'), "homeTeamAbb": ...

Performance problem with React-Native for-looping through a large array size

I'm currently facing a performance issue with the search function in my react-native app. The search involves scanning through an array of 15,000 elements for specific keywords. Surprisingly, the search performs well and quickly on Android devices, bu ...

What are the steps to fix the CORS problem when sending AJAX requests from a frontend to a Flask server?

My current project involves creating a web application with Flask for the backend and JavaScript for the frontend. However, I'm encountering challenges with CORS policy when attempting to send AJAX requests from my frontend to the Flask server. Below ...

I do not have access to display the registered information

I have successfully implemented a CRUD application in vue.js using a CDN, where Vue is imported directly into the file. However, I now want to migrate this CRUD functionality to a Vue project. I have created the project, installed axios, added the PHP file ...

Selenium Webdriver failing to select menuitem using text, xpath, or ID

Currently, I have some HTML code embedded in a SharePoint page that appears as follows: <span style="display:none"> <menu type='ServerMenu' id="zz28_RptControls" largeIconMode="true"> <ie:menuitem id="zz29_AddColumn" type="optio ...

Executing JavaScript functions externally from the Angular 6 application

I have a unique scenario where my angular 6 app is embedded within another application that injects JavaScript to the browser to expose specific functionalities to the angular app. For example, when running my angular app within this external application, ...

Enhancing the user experience by providing auto-complete suggestions while still maintaining the original form functionality

Encountering a curious bug that appears to be affecting only IE and Webkit browsers. I've set up a simple form as follows: <div id="output">Form output is shown here</div> <form id="myForm" action="#" method="post"> <input type= ...

Implement React-intl into the designated placeholder within the object

Currently facing an issue with the const inputProps in my code. I attempted to integrate React-intl into the react-autosuggest placeholder input, but now the placeholder text displays as: [Object object]. The getStepContent function is defined as follow ...

The Skeleton-Avatar and ImageButton components in MUI React have had their backgrounds reshaped into perfect ovals

I am facing an issue with the mui Stack where all the background shapes of the Skeleton Avatar and background area are turning into oval or ellipsoid shapes. I have tried setting equal width and height for Avatar but it has not solved the problem. Is ther ...

retrieve dynamically generated content following successful login using cURL

It's common knowledge that curl doesn't process JavaScript, it only fetches static HTML. This is why a simple curl command won't suffice for my needs. I'm not well-versed in PHP, still new to this field. From what I've gathered so ...

Utilizing identical ID values multiple times to link to the identical location

I am currently working on a horizontal grid project with 3 image squares. My goal is to create an action where clicking on any grid section will anchor the user down to a slideshow box displayed below the grid. Below is an example of one grid section and ...

Unlock the potential of HTML5 Datalist: A comprehensive guide on integrating it with

The latest version of HTML, HTML5, has introduced a new tag called datalist. This tag, when connected to <input list="datalistID">, allows for autocomplete functionality on web forms. Now the question arises - what is the most efficient approach to ...

Adding the Load More feature to your WordPress template for displaying custom posts

On my website, I am retrieving posts of a custom post type using get posts. However, I am retrieving all posts at once, but in my template, I want to display x number of posts per page and load the remaining posts using a load more button. <?php ...