Dave
Dave

Reputation: 2018

How to filter array in json object with computed

fetchData() {
      axios.get("api_url").then((response) => {
        this.dataArr = response.data;
      });
    },

I can't do this.dataArr = response.data.items.fruits; because I need to use this somewhere else like this.

dataArr looks like this:

{
   "items":{
      "fruits":[
         {
            "name":"banana",
            "type":"fruit",
    
         },
         {
            "name":"kiwi",
            "type":"fruit",
    
         },
  ]
}

I am trying to filter this in computed property:

filterData(){
   return this.dataArr.filter((item) => item.name )
}

But I am getting an error saying that this.dataArr is not a function, I need to get access to this.dataArr.items.fruits, but when I write it like that it's not working. Is there way to solve this?

Upvotes: 0

Views: 538

Answers (1)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

You should get access to the nested fruits array and it seems that you're trying to map that array by returning only the names in this case use map method:

 filterData(){
     if(this.dataArr.items && this.dataArr.items.fruits){
      return this.dataArr.items.fruits.map((item) => item.name )
      }else{
        return []
     }
    }

Upvotes: 1

Related Questions