Home > Enterprise >  Sorting and filtering object in vue js
Sorting and filtering object in vue js

Time:09-28

I have an object (skillList) containing an array of skills.

Object { data 
{ code:200,
data{[skill1, skill2, skill3, skill4] } }

Each skill has 3 properties

Skill name, skill description , skill status
Skill status = active or inactive only.

I am using vue and i am trying to filter the skills so that i only get active or inactive skills. this is my code:

methods:{
    async filterskill(filter){
      let response = await SkillService.getAllSkills(); 
      let skillList = response.data; 
      if(filter !== "All"){
        this.skillList = skillList.filter((skill) => { #getting an error at this line
          return skill.skill_Status === filter
        })
      }
    }

At the skillList.filter line i am constantly getting the following error:

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'skill')

Any help to solve this problem will be appreciated. I am using a .vue file so I cannot use things like javascript

console.log(response)

response log img

console.log(skillList)

skillList log img

CodePudding user response:

You have to apply filter() method on this.skillList.skill.

Live Demo :

new Vue({
  el: '#app',
  data: {
    skillList: {
        skill : [{
        name: 'S1',
        description: 'S1 description',
        status: 'active'
      }, {
        name: 'S2',
        description: 'S2 description',
        status: 'active'      
      }, {
        name: 'S3',
        description: 'S3 description',
        status: 'inactive'      
      }] 
    }
  },
  mounted() {
    const filteredList = this.skillList.skill.filter(obj => obj.status === 'active');
    console.log(filteredList);
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
</div>

  • Related