Creating a unique filter that combines and filters data from two separate API calls for

In my current scenario, I am making two different API calls using Axios in my application. The first call fetches a complete JSON file that populates a table, while the second call retrieves only categories. This setup is due to the complexity of the app, which is gradually being upgraded from an older framework. I have implemented two dropdowns - one for selecting years (which also builds the table) and the other for selecting categories. When the application loads, the table is initially populated with data for the current year.

My main query revolves around creating a custom computed filter to dynamically filter the table based on the selected category from the second dropdown. For example, upon selecting '2019' from the first dropdown, the entire table is loaded. Subsequently, choosing a specific category like "Name" should trigger an update that displays rows containing that particular category. Despite trying out various approaches, I'm struggling to conceptualize this particular functionality.

Here's a snippet of my current code:

data() {
 return {
  year:[],
  category:[] ,
  tableData:[],
 }
},

computed: {
 axiosParams(){
  const params = new URLSearchParams();
  params.append('year', this.year);
  return params;
 },

methods: {
 getYears: function(){  
  axios.get('myUrl', {
    params: this.axiosParams
     }).then((response) => {
    this.year = response.data;
    console.log(response.data)   
    this.tableData = response.data.result;
   })
   .catch((err) => {
    console.log(err);
  });
 },

 getCategory: function(){
   let category = [];
   axios.get('mySecondUrl').then((response, i) => {
    this.category = response.data
    for (var i = 0; i < category.length; i++) {
     let catType = i
     this.catType = response.data[i].name;
     console.log(catType);
    }
  })
  .catch((err) => {
    console.log(err);
  })
 }
}
created: {
 this.getYears();
 this.getCategory();
}

Here's the HTML markup:

<select v-model="selectedYear" @change="yearSelected">
 <option v-for="year in years" :key="year"> {{year}} </option>
</select>

<select v-model="selectedCat" >
 <option v-for="(item, index) in category" :item="item" 
 :key="index" :value="item.name"> {{ item.name }} </option>
</select>

Answer №1

Here's the structure of your tableData, which is an array of objects:

[
  { 
    "category":"Name", 
    "year":2019, 
    "username":"test", 
    "otherValues":[ 
      { 
        "someVal":30, 
        "otherVal":20 
      },
    ] 
  },
]

To filter items in this array based on a selected category name, JavaScript offers convenient solutions. One effective method to achieve this is by utilizing the filter() method. More information on how to use it can be found here.

The goal is to create a new array displaying the selected data or showing the entire tableData array if no category is selected. This functionality can be implemented as a computed property.

computed: {
  filteredTableData() {
    if (this.selectedCat !== null) {
      const filtered = this.tableData.filter(d => d.category === this.selectedCat)
      return filtered
    }
    return this.tableData
  },
}

It's assumed that you initialize selectedCat in your data with a value of null. Consequently, when a category is selected, it will satisfy the 'if' condition and generate a new array ('filtered') containing elements from 'tableData' that match the specified category. If no category is chosen, the complete tableData array is returned.

When accessing 'tableData' in the template using v-for="data in tableData", make sure to update it to

v-for="data in filteredTableData"
.

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

The select box in Material UI is not displaying the data as expected

I'm currently tackling an issue where, upon every click of an icon, a select box (from material ui) needs to be displayed with a few options inside it. The functionality should show the select box each time the icon is clicked. Here's a brief sum ...

What is the best way to retrieve all variable names from a JSON file?

Is there a way to extract an array of variable names from JSON data? For instance, if I'm given: { "Java": 20526, "Shell": 292, "Groovy": 213 } I aim to transform it into an array like this: String[] {"Java", "Shell", "Groovy"} Any suggestio ...

Revising Vue for lazy loading upgrades

Facing a challenge in optimizing the lazy loading of components in my application. I aim to display a loading spinner while any component is being loaded, as well as handling errors with the same approach, resulting in redundant code. export default c ...

Creating a Client-side Web Application with Node.js

As I search for a versatile solution to bundle an HTML5 web application (without server dependencies) into a single executable app using node.js and the Linux terminal on Ubuntu, I have experimented with tools like wkpdftohtml and phantomjs. However, these ...

Storing a Vue/JS element reference in a constant using Typescript

In my template, I have one form element and one button element: <button type="submit" id="ms_sign_in_submit" ref="submitButton" class="btn btn-lg btn-primary w-100 mb-5"> </button> Wi ...

Is it true that Laravel Sanctum only creates access tokens?

I am trying to grasp the essential flow of laravel sanctum within a SPA(vuejs) application. From what I have gathered so far: A middleware is set up for API authentication Upon user login, access_tokens are generated and sent back to the frontend. Th ...

Tips for extracting only a portion of the JavaScript timestamp

I have a JavaScript timestamp that reads Tue Sep 30 2014 12:02:50 GMT-0400 (EDT). When I use the .getTime() method, I get 1412092970.768 Typically, this timestamp represents a specific time of today. My question is whether it's possible to extract o ...

Assign a CSS class to a DIV depending on the vertical position of the cursor

The website I am currently developing is located at Within the site, there is a collection of project titles. When hovering over a project title, the featured image is displayed directly below it. I would like to change the positioning of these images to ...

Unable to modify the .top attribute style in elements within an arraylist using JavaScript

I need to align multiple images in DIVs on the same line by setting their Top value to match the first image in the array. Here is the code I am struggling with: (addBorder function is called when divs are clicked) <div class="DRAGGABLE ui-widget-cont ...

Transforming a JSON object with Backbone and Laravel

When my Backbone application sends results to Laravel via a POST request, the data is received like this: $input = Input::json(); The returned data is in the form of a JSON object, not a string. Initially, I attempted to use json_decode to access its pro ...

Choose an image to be displayed at either full width or full height, depending on which dimension is reached first

I have a query regarding resizing an image within a div to either 100% width or 100% height of the containing div. Despite setting max-height and max-width to 100% as recommended here, I still encounter overflow issues without wanting to crop the image usi ...

Extracting information from $router within a Vue component

I need to manage the status of users who access my system through a URL generated by a QR Code. In my routes.ts file, I'm checking if the user is logged in and then redirecting them accordingly. if (store.getters.isLogged && to.path === 'QRCode& ...

Displaying retrieved data following AJAX request in ASP.NET MVC is currently not functioning

I have a situation where I need to populate two <p> fields with text Below is the HTML code snippet: <p id="appId" style="visibility: hidden;"></p> <p id="calculationId" style="visibility: hidden;"></p> I am making an AJAX ...

HTML5 for advanced positioning and layering of multiple canvases

I have 2 canvas layers stacked atop each other, but I need to position them relative to the entire page. The dimensions of both layers are fixed at a width of 800 and a height of 300. My goal is to center the canvas layers regardless of screen size, with ...

The features of findOneAndRemove and findOneAndUpdate are not functioning optimally as expected

Attempting to create a toggle similar to Facebook's "like" feature. The code functions correctly when there are no existing "likes." It also deletes properly when there is only one "like" present. However, issues arise when multiple likes accumulat ...

Display a substitute image if there is no internet connection available to load the Google Map Canvas

I have a WebApp that runs locally, but it's possible that users may not always have access to 3G/WiFi when using the app. This means that the Google Map will not load without an internet connection since it requires the web API. In order to provide a ...

A guide to displaying API response data in a React JS application

As a beginner in react JS, I've encountered a persistent issue. Here is the code: import React from 'react'; class SearchForm extends React.Component { async handleSubmit(event){ event.preventDefault(); try{ const url ='/jobs/ ...

What are the steps to create a ListView in a ChatApp for organizing and viewing all conversations?

In developing my chat application, I am considering using a List to organize all the chats. Since my app is integrated with Firebase, I am faced with the decision of whether to utilize a FlatList and store all data locally or in a Firebase database. What ...

What is the best way to ensure a table is responsive while maintaining a fixed header? This would involve the table scrolling when it reaches the maximum viewpoint, while also keeping

Can anyone help me create a responsive table with a fixed header that scrolls when it reaches the maximum viewpoint without scrolling the entire page? I've tried using box-sizing: border-box; and overflow-x:scroll; but it didn't work. Any suggest ...

How can child components in ReactJS be conditionally rendered based on the status of userData loading?

It seems like there might be an issue with how we handle user login in our application. Whenever a user logs in, the redux state is updated with the server response. Many components rely on this logged-in status. We pass the currentUser object down to all ...