0

I'm creating a https://github.com/MIt9/angular-4-data-table with my data from firebase. My problem is, i have route naviagation with 'name' parameter. I click on link and i want to display only this which equals to my passed 'name' parameter. I click on link and shows me all products from db in Array of objects. How to filter this? I need to do filter before pass it to my data-table.

component.ts file:

productCategory: Product[];
  filteredProducts: any[];
  subscription: Subscription;
  tableResource: DataTableResource<Product>;
  name;
  items: Product[] = [];
  itemCount: number;

  constructor(
    private productService: ProductsService,
    private route: ActivatedRoute
  ) {
    this.route.paramMap.subscribe(params => {
      let name = params.get("name");
      this.name = name;
      this.subscription = this.productService.getAll().subscribe(products => {
        this.filteredProducts = this.productCategory = products;

        // here i think i want to filter input data and pass this into variable
        let category = products.filter(products => products.category);
        console.log(category);

          this.InitializeTable(category);


      });

    });
  }

  private InitializeTable(products: Product[]) {
    this.tableResource = new DataTableResource(products);
    this.tableResource.query({ offset: 0 }).then(items => (this.items = items));
    this.tableResource.count().then(count => (this.itemCount = count));
  }

  reloadItems(params) {
    if (!this.tableResource) return;
    this.tableResource.query(params).then(items => (this.items = items));
  }
3
  • myArray.find( a => a.name === 'thing') -- does regular JS array filtering not work? Commented Mar 13, 2018 at 15:51
  • it works by it display only first record in console, and later shows error TypeError: this.items.slice is not a function Commented Mar 13, 2018 at 15:54
  • Ok i found, pls answer this but change find to filter :) Commented Mar 13, 2018 at 15:55

1 Answer 1

3

Javascript supports a native filter method. (Also a find if you only want the first; it is unclear from your question if this is sufficient.)

So, for example, if you want to find the first item in your array that has a name attribute that matches some target "name", you would do:

let myItem = myArray.find(item => item.name === "name");

Alternatively, if you want to filter down your array so you only have those items that match your target "name", you can use the similar filter method:

let myItems = myArray.filter(item => item.name === "name"); // myItems is an array

You can read more about these functions by referring to MDN:

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

1 Comment

Thanks for your answer!