0

I have an array of vehicles objects. I have tabs for different vehicle types for eg. 2-wheeler, 4-wheeler etc. While adding vehicle to the collection I am adding its type so my object kind of looks like this.

vehicles:[{
  key1:{ name: "Altima",type:"4-wheeler" },
  key2:{ name: "Harley",type:"2-wheeler" },
  key3:{ name: "Jeep",type:"4-wheeler" },
}]

Now I am retrieving all vehicles from server and want to add filter on frontend based on type. How can I add the filter for different tabs?

8
  • What did you try to do? Commented Dec 20, 2017 at 7:05
  • you can use filter method of the array Commented Dec 20, 2017 at 7:10
  • how to get all data form server could you add code here please Commented Dec 20, 2017 at 7:11
  • @AddWebSolutionPvtLtd Sorry its a part of project. This is just an example. But something like this. I am using firebase as my database.. Commented Dec 20, 2017 at 7:23
  • @Aravind by filter do you mean pipe? If yes, I am bit new to this so not sure how to implement one. Commented Dec 20, 2017 at 7:24

2 Answers 2

1

You can implement a pipe using array.filter and use it as follows,

export class MyFilter implements PipeTransform {

    transform(items: any[], term: any[]): any {
      if (!term) 
        return items;
      return items.filter(item => item.prefix.indexOf(term) > -1);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

try like below code

 vehicles:any = [{
                  key1:{ name: "Altima",type:"4-wheeler" },
                  key2:{ name: "Harley",type:"2-wheeler" },
                  key3:{ name: "Jeep",type:"4-wheeler" },
                }];


datavehicle = [];


ngOnInit() {
   let vihicledata= this.vehicles[0];
   var array = Object.keys(vihicledata).map(function(k) {
     return vihicledata[k]
   });

    for(let i =0 ;i < array.length;i++){
      if(array[i].type == "4-wheeler"){
        this.datavehicle.push(array[i]);
      }
    }
    console.log('vehicle=>',this.datavehicle)
}

1 Comment

This will definitely work but was looking more efficient solution (may be involving filter).

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.