1

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.

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Got one more question. If I have one component with dropdown buttons, and in another component I fetch data and display it. How can I filter the data through component where I have only dropdown button?
You're welcome. There are a few ways to share data among components. If the components are not related in a simple parent/child relationship, Vuex is the best solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.