vue filtering values from JSON with computed-function

谁说胖子不能爱 提交于 2021-01-29 06:16:34

问题


How can I filter my array of JSON-data:

This is my markup:

  <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>

This is my 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 my API function to get the JSON data: vacciResults is fetching the states.

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

        }

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

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

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


回答1:


The problem here was

this.vacciResults is an object and you are tried array operations on it in your computed property

below is modified computed property


     computed: {
            filteredList() {
    //********* changes added 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
             }  
      }



来源:https://stackoverflow.com/questions/65827954/vue-filtering-values-from-json-with-computed-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!