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

Incorporating D3.js into Angular 6 for interactive click events

Currently working on building a visual representation of a tree/hierarchy data structure using d3.js v4 within an Angular environment. I've taken inspiration from this particular implementation https://bl.ocks.org/d3noob/43a860bc0024792f8803bba8ca0d5e ...

Discovering items within an array using Vue.js or JavaScript

I have an array of elements in Vue.js where I need to manipulate some data. For example, I have a select dropdown that displays company information with corresponding tags. These tags are at one sub level and are combined into one before being stored in th ...

What is the best way to organize a data tree in JavaScript for easy parsing on the frontend?

I'm struggling with a unique tree data structure in my code. Each node is represented by an object, and I need to transfer the entire tree to the front-end. Unfortunately, JavaScript's limitation on using objects as keys prevents me from implemen ...

Utilizing puppeteer-core with electron: A guide

I found this snippet on a different Stack Overflow thread: import electron from "electron"; import puppeteer from "puppeteer-core"; const delay = (ms: number) => new Promise(resolve => { setTimeout(() => { resolve(); }, ms); }) ...

Utilizing JSON for HTML conversion in Codeigniter

public function getCrew(){ $search = $this->input->post('name'); if($this->input->post('ajax') && (!empty($search))){ $result = $this->model->getNames($search); foreach($result as $r){ ...

Amazon Lex: Transforming Speech to Text with Audio Technology

Is there a JavaScript SDK provided by Amazon for converting audio files to text using Amazon Lex? I am currently working on a Node.js application and would like to achieve this functionality. ...

Executing Angular CLI tasks using a script file rather than directly from the CLI? Embracing the power of Localization and Internationalization

Our Angular 2 app is gearing up for internationalization/localization, and I am looking to create scripts that can handle tasks such as generating translation source files or building/serving the application with translations in a specific language. Inste ...

Using Node.js, express, jade, highcharts, and a 2D array

Greetings, I am relatively new to the realm of javascript/node.js/express/jade/highcharts etc... The predicament at hand is as follows: I have a template that takes in a few parameters which are pre-processed in my router code. These parameters are group ...

Angular JS is facing difficulties in being able to call upon another directive

I'm encountering an issue where including another directive related to the current one results in the following error message Error: [$compile:ctreq] http://errors.angularjs.org/1.2.10/$compile/ctreq?p0=myApp.pagereel&p1=ngTransclude Script.js ...

Instead of loading the HTML into the div, Ajax is now sending me the link instead

I have just begun working on a new laravel project and am currently working on the user profile page, which will include a sidebar with links like Portfolio, Account Settings, etc. My goal is to dynamically load each page into a div when a link in the side ...

Retrieving URL parameters within an API route handler in Next.js

Within my client component called GetUserInfoButton, I initiate a GET request using the URL format of http://localhost:3000/test/users/[id]. The [id] in this URL is represented by an alphanumeric sequence similar to MongoDb. My intention within the file a ...

Understanding the impact of event loop blocking and the power of asynchronous programming in Node JS

I am new to Node.js programming and I really want to grasp the core concepts and best practices thoroughly. From what I understand, Node.js has non-blocking I/O which allows disk and other operations to run asynchronously while JavaScript runs in a single ...

You need to pass a function as the first parameter when using passport-local-mongoose as a schema plugin

I've been struggling with implementing passport-local-mongoose in my server. I followed a tutorial video but encountered an issue that wasn't addressed in the video - even though my database is connected to mongodbatlas. The error message "First ...

Iterating through two classes in a Javascript loop

Hello, I'm facing a small obstacle that I'm hoping to overcome using JavaScript/jquery. Essentially, I have multiple div classes and I want to create a loop that adds a class to specific divs without manually assigning an id to each one. The goal ...

The AJAX function fails to trigger the MVC controller method

I'm attempting to enable inline editing by cell, rather than by row, when double-clicking. Although the initial setup is working, it's not updating the record as expected - the "SaveCustomer" call to the controller isn't triggered. Can anyon ...

The element.find() function in Angular struggles to locate input elements nested within other elements

I have been working on a directive that has the following template (simplified): <table> <tr> <td> <input type="text"/> </td> <td> <inpu ...

What is the best way to show the interior color of a cube in three.js?

My plan is to create a room using THREE.js starting from a basic cube. Here's what I have written so far: function loadModelcube() { console.log("Function executed successfully"); cube.traverse( function( node ) { if( node.material ) { ...

React js: Changing Material-UI functional code to class component results in TypeError

After utilizing the material ui login page code, I discovered that it is a functional component. To meet my specific requirements, I decided to convert it into a class component. However, during the conversion process, an error was encountered: "Cannot ass ...

Exploring object properties within arrays and nested objects using ReactJS

Within the react component PokemonInfo, I am looking to extract the stats.base_stat value from the JSON obtained from https://pokeapi.co/api/v2/pokemon/1/. The issue lies in the fact that base_stat is nested inside an array called stats. My assumption is t ...

Can a div's style be modified without an id or class attribute using JavaScript or jQuery?

Is it possible to change the style of a div that doesn't have an id or class assigned to it? I need some assistance with this. Here is the div that needs styling: <div style="display:inline-block"> I would like the end result to look somethin ...