按属性值过滤对象数组 [英] Filter array of objects by property value
本文介绍了按属性值过滤对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是Angular和Observable的新手.我从JSON文件中获得了产品列表.
I'm new with Angular and observables. I'm getting from a JSON file a list of products.
产品.服务
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
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?
代码不起作用
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);
这篇关于按属性值过滤对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文