Reputation: 333
I want to filter an object by states-name (e.g. Berlin, Bayern ...). This is my response from the API.
"states":{
"Bayern":{
"total":13124737,
"rs":"09",
"vaccinated":254916,
"vaccinated_by_accine":{
"biontech":246384,
"moderna":8532
},
"difference_to_the_previous_day":4878,
"vaccinations_per_1000_inhabitants":19.42,
"quote":1.94,
"2nd_vaccination":{
"vaccinated":67418,
"difference_to_the_previous_day":8102
}
},
"Berlin":{
"total":3669491,
"rs":"11",
"vaccinated":74605,
"vaccinated_by_accine":{
"biontech":73012,
"moderna":1593
},
"difference_to_the_previous_day":3306,
"vaccinations_per_1000_inhabitants":20.33,
"quote":2.03,
"2nd_vaccination":{
"vaccinated":18158,
"difference_to_the_previous_day":953
}
},
This is my function in computed section: (searchstring is an input-field in my markup)
computed: {
filteredList() {
let filter = {};
let searchString = this.searchstring.toLowerCase();
Object.keys(this.vacciResults).forEach(key => {
filter[key] = this.vacciResults[key].filter(function(item){
return item.toLowerCase().includes(searchString);
});
});
return filter
},
...
this.vacciResults = res.states;
I get this error, why? item should contain the states name.
new function:
filteredList() {
let searchString = this.searchstring.toLowerCase();
return Object.keys(this.vacciResults).reduce((carry, key) => {
carry[key] = Object.keys(this.vacciResults[key]).filter(item => item.toLowerCase().includes(searchString))
return carry
}, {})
},
Upvotes: 1
Views: 54
Reputation: 50787
Your this.vacciResults[key]
is yet another object so you'll need to leverage Object.keys()
on it as well. I've just used reduce
here for clarity.
let searchString = this.searchstring.toLowerCase();
return Object.keys(this.vacciResults).reduce((carry, key) => {
carry[key] = Object.keys(this.vacciResults[key]).filter(item => item.toLowerCase().includes(searchString))
return carry
}, {})
Upvotes: 1