按属性值过滤对象数组

时间:2018-12-03 04:22:27

标签: javascript angular typescript rxjs

我是Angular和Observable的新手。 我从JSON文件中获取产品列表。

产品。服务

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;
}

一切正常,但我想过滤响应以仅获取available == true

的产品

我在服务和组件方面尝试了一些方法,但是没有任何效果。如何以适当的方式实现这一目标?

代码不起作用

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响应(未过滤)

 { "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"
  }
  ]}

3 个答案:

答案 0 :(得分:1)

尝试一下。

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);

答案 1 :(得分:0)

使用pipe内的filter运算符并进行常规订阅

filterProducts(): Observable<Product[]>{

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

}

答案 2 :(得分:0)

这应该有效。

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