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