按属性值过滤对象数组

2024-01-12

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

产品.服务

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

产品.组件

products: Product[];

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

产品.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"
  }
  ]}

尝试这个。

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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

按属性值过滤对象数组 的相关文章

随机推荐