Filter array of objects by property value

↘锁芯ラ 提交于 2020-01-30 10:35:07

问题


I'm new with Angular and observables. I'm getting from a JSON file a list of products.

products.service

getProducts(): Observable<Product[]>{
    return this._http.get<Product[]>(this.configUrl); 
}

products.component

products: Product[];

getProducts(): void{
    this.productsService.getProducts()
        .subscribe(products => this.products = products);
}

product.ts

export interface Product {
    "quantity": number;
    "price": string;
    "available": boolean;
    "sublevel_id": number;
    "name": string;
    "id": string;
}

Everything is working fine but I would like to filter the response to get only the products where available == true

I tried in service and component some approaches but nothing worked. How can I achieve this in a proper way?

Code not working

this.products = this.products.filter(product => {
  return product.available == true
});



filterProducts(): Observable<Product[]>{

    return this.getProducts()
        .pipe(map(products => products
        .filter(product => product.available === true)));

}

JSON response (not filtered)

 { "products": [
  {
    "quantity": 308,
    "price": "$8,958",
    "available": false,
    "sublevel_id": 3,
    "name": "aute",
    "id": "58b5a5b1b6b6c7aacc25b3fb"
  },
  {
    "quantity": 891,
    "price": "$5,450",
    "available": true,
    "sublevel_id": 3,
    "name": "mollit",
    "id": "58b5a5b117bf36cf8aed54ab"
  },
  {
    "quantity": 698,
    "price": "$17,001",
    "available": false,
    "sublevel_id": 10,
    "name": "eiusmod",
    "id": "58b5a5b18607b1071fb5ab5b"
  }
  ]}

回答1:


Try this.

let o = { "products": [
  {
    "quantity": 308,
    "price": "$8,958",
    "available": false,
    "sublevel_id": 3,
    "name": "aute",
    "id": "58b5a5b1b6b6c7aacc25b3fb"
  },
  {
    "quantity": 891,
    "price": "$5,450",
    "available": true,
    "sublevel_id": 3,
    "name": "mollit",
    "id": "58b5a5b117bf36cf8aed54ab"
  },
  {
    "quantity": 698,
    "price": "$17,001",
    "available": false,
    "sublevel_id": 10,
    "name": "eiusmod",
    "id": "58b5a5b18607b1071fb5ab5b"
  }
  ]}

let filtered = o.products.filter(p => p.available===true)
console.log(filtered);



回答2:


use the filter operator inside the pipe and do the normal subscription

filterProducts(): Observable<Product[]>{

return this.getProducts()
    .pipe(
       filter(products =>  product.available )
     )

}



回答3:


This should work.

getProducts(): void{
    this.productsService.getProducts()
        .subscribe(products => this.products = products.filter(product=>product.available==true));
}


来源:https://stackoverflow.com/questions/53587449/filter-array-of-objects-by-property-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!