0

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;

result of console log vacciResults

asked Jan 21, 2021 at 12:58
3
  • vacciResults ...is that your response object? Commented Jan 21, 2021 at 13:02
  • yes, this is the response object: this.vacciResults = res.states; Commented Jan 21, 2021 at 13:05
  • 1
    add that code as well in your question Commented Jan 21, 2021 at 13:06

1 Answer 1

0

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
 } 
 }
answered Jan 21, 2021 at 13:15

15 Comments

wow, that's great! I will try it at once. THX
unfortunately, it does not work. The list is not displayed :(
try printing console logs of this.vacciResults, this.searchString inside your computed property
OK, have tried. No results are shown in the list.
then to get more understanding pls share the entire code of the file in the question
|

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.