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;
Ralf BordéRalf Bordé
asked Jan 21, 2021 at 12:58
-
vacciResults ...is that your response object?Amaarockz– Amaarockz2021年01月21日 13:02:35 +00:00Commented Jan 21, 2021 at 13:02
-
yes, this is the response object: this.vacciResults = res.states;Ralf Bordé– Ralf Bordé2021年01月21日 13:05:12 +00:00Commented Jan 21, 2021 at 13:05
-
1add that code as well in your questionAmaarockz– Amaarockz2021年01月21日 13:06:57 +00:00Commented Jan 21, 2021 at 13:06
1 Answer 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
}
}
answered Jan 21, 2021 at 13:15
15 Comments
Ralf Bordé
wow, that's great! I will try it at once. THX
Ralf Bordé
unfortunately, it does not work. The list is not displayed :(
Amaarockz
try printing console logs of this.vacciResults, this.searchString inside your computed property
Ralf Bordé
OK, have tried. No results are shown in the list.
Amaarockz
then to get more understanding pls share the entire code of the file in the question
|
lang-js