在Vue中筛选json响应



我在Vue中过滤json响应时遇到问题。

return this.offers.filter(type => type.offers == 'Junior');

每当我将其保留为return this.offers时,在我的html中就会显示:

{"-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" } }

但我只希望出现具有"skill": "Junior"的字段。

您的JSON是一个对象,但filter仅适用于数组。您可以将用于。。。在计算的循环中重新格式化并按您喜欢的方式过滤:

computed: {
filteredOffers() {
const filteredOffers = [];
for(const key in this.offers) {
if (this.offers[key].skill == 'Junior') filteredOffers.push(this.offers[key]);
}
return filteredOffers;
}
}

这将返回所需对象的数组。如果你只想在你的模板中原始显示它们:

<div id="app">
{{ filteredOffers }}
</div>

这里有一个演示:

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>

最新更新