Search code examples
javascriptvue.js

vuejs filter is not a function error


I've got a very basic array:

specialityTest: [{person:'nurse', text:'text1'}, 
{person:'nurse', text:'text1'}, 
{person:'physician', text:'text1'}, 
{person:'physician', text:'text1'}]

I'm trying to filter this using basic filter function:

      this.specialityTest.filter((person) => {
        return (person =="physician")
      })

and then copy filtered array:

  methods: {
   seedSpeciality(){
      this.nurseListSpeciality2 = JSON.parse(JSON.stringify(this.specialityTest.filter(
      (person) => {
        return (person =="physician")
      })))
  },
 }

and this is not working for me... I've got error:

Uncaught (in promise) TypeError: this.specialityTest.filter is not a function at VueComponent.seedSpeciality (AddOfferDialog.vue?f4fc:1771) at VueComponent.boundFn [as seedSpeciality].

What am I doing wrong here?

edit: I run this function from api call:

  fetchSpecialityArray(){
    this.$http.get('http://127.0.0.1:8000/api/speciality')
      .then(response => response.json())
      .then(result => this.specialityTest = result).then(this.seedSpeciality.bind(this))
  },

Solution

  • For me it works fine.Take a look:

    <div id="app">
      <button @click="filter">Filter</button>
    </div>
    
    new Vue({
      el: "#app",
      data: {
        specialityTest: [
          {person:'nurse', text:'text1'}, 
          {person:'nurse', text:'text1'}, 
          {person:'physician', text:'text1'}, 
          {person:'physician', text:'text1'}
        ]
      },
      methods: {
        filter() {
            let filtered = this.specialityTest.filter((el) => {
            return (el.person =="physician")
          })
          console.log(filtered)
        }
      }
    })
    

    You are looping through array of object with filter function so in each loop you get the object.So if you use el.person == "physician" it will work fine

    Take a look to my jsfiddle