Utilizing Vue's computed function to filter values from a JSON dataset

How do I efficiently filter an array of JSON data?

Here is the code snippet:

  <div v-if="vacciCounter">
        <b-card no-body class="mb-2" v-for="(stateObject, state) in filteredList" v-bind:key="state">

            <div style="margin:10px 10px 10px 10px;">
                <h5>{{ state }}</h5>

Here is the filtering function:

  computed: {
        filteredList() {
            if (this.vacciResults.length > 0) {  
                return this.vacciResults.filter(entry => {
                    return entry.state.toLowerCase().includes(this.searchstring.toLowerCase())

                });
            } 
        },
      
        getStates() {
         return this.vacciResults; // assuming that you have stored the response in a variable called 'output' defined in the data section
           }    

This is the API function fetching the JSON data: vacciResults contains the states information.

fetch(vacciURL, {
        method: 'get',
        headers: {

        }

        }).then(res => res.json())
        .then(res => {

            this.status = '';
            this.searchBtnDisabled = false;
            

            this.vacciCounter = res.vaccinated;
            this.vacciResults = res.states;

https://i.sstatic.net/O93O6.png

Answer №1

The issue at hand was

that `this.vacciResults` is an object, and you attempted to perform array operations on it within your computed property.

Here is the updated computed property:


     computed: {
            filteredList() {
    //********* Updated code below ***********
                if (this.searchString !== '' && Object.keys(this.vacciResults).length > 0) { 
                      let filterObject = {};           
                      Object.keys(this.vacciResults).forEach(state => {
                          if(state === this.searchString.toLowerCase()) filterObject[state] = this.vacciResults[state];
                      });
                  return filterObject;
                 }
             return this.vacciResults;              
            },
          
            getStates() {
             return this.vacciResults; // assuming that you have stored the res.states in a variable called 'vacciResults' defined in the data section
             }  
      }

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

Using vue-i18n in Nuxt.js: a guide for utilizing it outside components

I have integrated the plugin vue-i18n into my Nuxt.js-powered SPA for efficient translation handling. It allows me to easily access messages within components, just like this: $t('footer.press') However, I am facing an issue on how to retrieve t ...

JavaScript code failed to run

I am currently attempting to invoke a JavaScript script to export a chart from the PrimeFaces chart component. The issue I am facing is that the base64str variable appears to be null, and the script responsible for populating this value is not being called ...

Unable to display a recursive component with Vue3 CDN

I am currently working on a project using Vue3 CDN because the project environment cannot run npm. I have been trying to create a component with html+CDN, but when attempting to create a recursive component, it only renders the top-level element. Is there ...

Navigating iFrames using Phantomjs Watir

Trying to access a login page using my script: Using PhantomJS and Watir. The issue with the login page is that the login textfields are within an iFrame: <iframe class="hiFrame" data-reactid=".0.0.0.1.0.1.0.0.$frame" src="https://instagram.com/accou ...

Navigate to the date selector and select the following month

https://i.sstatic.net/AdWVs.png <button class="mat-calendar-next-button mat-icon-button" mat-icon-button="" type="button" ng-reflect-disabled="false" aria-label="Next month"><span class="mat-button-wrapper"></span><di ...

Using numerous textures for a single mesh in THREE.js

I am working with an OBJ file that utilizes four textures. The UV coordinates in the file range from (0, 0) to (2, 2), where (0.5, 0.5) corresponds to a coordinate in the first texture, (0.5, 1.5) is a UV coordinate in the second texture, (1.5, 0.5) repres ...

Encountering a problem while trying to start the server with npm run server in my Vue JS

For this project, I implemented PWA by using vue add pwa through Vue Cli. As part of the installation process, two packages were added: "@vue/cli-plugin-pwa": "~5.0.0", "register-service-worker": "^1.7.2" However, ...

Newbie exploring the world of Rails and jQuery

While I am making progress with jQuery and successfully linking js.erb files to controller actions, I have encountered a roadblock. I am unsure of how to make a button, which is not associated with a controller action, trigger specific jQuery commands. My ...

Retrieve the value of an AngularJS expression and display it in a window alert using AngularJS

Hey there, I am in the process of trying to display the value of an expression using AngularJs As a beginner in angular, I am working on figuring out how to retrieve the value of the expression either with an alert or in the console. I'm utilizing A ...

Seeking a solution for resolving the problem with HTML1402 when using jquery URL in Internet Explorer?

Why is it that only IE (and not any other browser) gives me the error HTML1402: Character reference is missing an ending semi-colon “;” with this code: <!DOCTYPE HTML> <html> <head> <script src="http://code ...

Exploring the Observable object within Angular

As I delve into learning Angular through various tutorials, I encountered a perplexing issue regarding my console displaying an error message: ERROR in src/app/employee/employee.component.ts:17:24 - error TS2322: Type 'IEmployee' is not assignab ...

What is the best way to form a singular entity and insert numerous sets of key-value pairs within it?

Currently, I am working on creating an object that contains multiple key-pair values obtained from an API response. My goal is to transform the API response into a single object, but the code I have written does not produce the desired result. This is my ...

Issue with Ajax not functioning properly for Jquery autocomplete feature in PHP

The ajax request shown below is creating an array of values that I want to use in a jQuery autocomplete function: var whatever = []; $.ajax({ url: "myScript.php", success: function (response) { whatever = response.split(","); } }); Th ...

Having trouble rendering the map on my React page

Struggling to display a list of objects in a React component. The data is fetched correctly and logged to the console, but for some reason, the object names are not rendering in a list on the screen when the page reloads. Can't figure out where the er ...

Is it possible to combine JavaScript objects using TypeScript?

Currently, I am dealing with two objects: First Object - A { key1 : 'key1', key2 : 'key2' } Second Object - B { key1 : 'override a' } I am looking to combine them to create the following result: The Merged Re ...

How can I toggle a clicked switch in React MUI instead of all switches?

This is the current state in my parent component: const [feedbackType, setFeedbackType] = useState({ manual: true, auto: false, }); I am passing this state as a prop to the child component. In the child component, I have the following code: co ...

What is the method for linking the value of a button in Vue.js?

I am trying to bind values of buttons in Vuejs. Here is what I have so far: <b-button-group> <b-btn value="one" v-model="stateButtons">one</b-btn> <b-btn value="two" v-model="stateButtons">two</b-btn> <b-b ...

Displaying text from an array in a div using JavaScript with a 2-second delay

I am relatively new to this, so please forgive me if something is not quite right. I have an array filled with different strings of text, and I want to display each string in an HTML div with a 2-second delay between each line. While I have managed to show ...

Lerna: The Ultimate Guide to Installing External Packages Across Multiple Projects

We utilize Lerna for managing our mono-repo projects, and I am seeking the most effective method to install an external package in my projects while ensuring they all use the same version. Here is my project structure (my-Main-A and my my-Main-B both depe ...

What are the steps for utilizing the Object.entries(...) method along with .forEach and .every

Using a constant queryModifier = {price: "lessThan", weight: "greaterThan"}, I am filtering a list. const queryKeys = keys: { price: '1000', weight: '1000' } const list = [ { // object data here }, { // o ...