Reputation: 2018
I am having trouble with filtering a json response in Vue.
return this.offers.filter(type => type.offers == 'Junior');
Whenever I leave it as return this.offers
, in my html this is being displayed:
{"-MN5agCddYAdy7c8GSSz": { "companyName": "dawdwad", "image": "da", "jobDescription": "dada", "location": "daw", "salary": "dadaw", "skill": "dawda", "tags": "dada", "title": "dwa" }, "-MN7vsTsNohgQigd3S26": { "companyName": "ejadfjaq", "image": "", "jobDescription": "dada", "location": "2sjawdja", "salary": "40324032", "skill": "Junior", "tags": "ux", "title": "fawd" } }
But I want only the fields with "skill": "Junior"
to appear.
Upvotes: 1
Views: 42
Reputation: 63099
Your JSON is an object but filter
only works on arrays. You can use the for...in loop in a computed to reformat it and filter it the way you like:
computed: {
filteredOffers() {
const filteredOffers = [];
for(const key in this.offers) {
if (this.offers[key].skill == 'Junior') filteredOffers.push(this.offers[key]);
}
return filteredOffers;
}
}
This returns an array of the objects you want. If you just want to display them raw in your template:
<div id="app">
{{ filteredOffers }}
</div>
Here's a demo:
new Vue({
el: "#app",
data() {
return {
offers: {
"-MN5agCddYAdy7c8GSSz": {
"companyName":"dawdwad",
"image":"da",
"jobDescription":"dada",
"location":"daw",
"salary":"dadaw",
"skill":"dawda",
"tags":"dada",
"title":"dwa"
},
"-MN7vsTsNohgQigd3S26":{
"companyName":"ejadfjaq",
"image":"",
"jobDescription":"dada",
"location":"2sjawdja",
"salary":"40324032",
"skill":"Junior",
"tags":"ux",
"title":"fawd"
}
}
}
},
computed: {
filteredOffers() {
const filteredOffers = [];
for(const key in this.offers) {
if (this.offers[key].skill == 'Junior') filteredOffers.push(this.offers[key]);
}
return filteredOffers;
}
},
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
{{ filteredOffers }}
</div>
Upvotes: 1