我正在创建我的商店应用程序,我想使用过滤器到我的商店列表中的所有产品。我的产品表分为多个类别和后来的产品ID。当我手动设置路径 / products / apple 时,它正在运行并过滤我新的苹果项目数组。但我想对所有产品实施此功能。我如何跳过该类型列并进行更深入的搜索?
我的服务:
getAll() {
return this.db.list('/products/ps4');
}
我的AppComponent.ts
export class AppComponent implements OnDestroy {
products: {name: string}[];
filteredProducts: any[];
subscription: Subscription;
today: Date = new Date();
constructor(
private auth: AuthService,
router: Router,
private userService: UserService,
private productsService: ProductsService
) {
setInterval(() => {
this.today = new Date();
}, 1);
auth.user$.subscribe(user => {
if (user) {
userService.save(user);
let returnUrl = localStorage.getItem("returnUrl");
router.navigateByUrl(returnUrl);
}
});
this.subscription = this.productsService
.getAll()
.subscribe(products => (this.filteredProducts = this.products = products));
}
filter(query: string) {
this.filteredProducts = (query) ?
this.products.filter(p => p.name.toLowerCase().includes(query.toLowerCase())) : this.products;
console.log(query);
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
和我的json文件:
<input #query (keyup)="filter(query.value)" type="text" class="form-control" placeholder="Search...">
<ng-container>
<div *ngFor="let f of filteredProducts">
{{ f.name }}
</div>
</ng-container>
</div>
EDITED
filter(query: string) {
this.filteredProducts = (query) ?
this.products.map(category => {
return category[Object.keys(category)[0]]
}).filter(p => p.name.toLowerCase().includes(query.toLowerCase())) : this.products;
console.log(this.filteredProducts);
}
答案 0 :(得分:0)
由于您的JSON不是数组,因此您无法在每个条目上直接使用map
,但可以使用Object.keys
和reduce
伪造它。这样,您可以处理每种产品类型并在每个
const filteredProducts = Object.keys(products).reduce((result, key) => {
const product = products[key];
result[key] = product.filter(p => p.name.toLowerCase().includes(query.toLowerCase()));
return result;
}, {});
答案 1 :(得分:0)
老实说,你的问题对于你想要最终结果的确切格式有点模糊。以下将所有产品展平为一个根产品值的数组,我想这就是你要求的......
var products = [{
apple: [{
category: 'apple',
name: 'cold apple',
producer: 'producer1',
screen: 'screen1'
},
{
category: 'apple',
name: 'name2',
producer: 'producer2',
screen: 'screen2'
}
]
},
{
coolers: [{
category: 'cooler',
name: 'name3'
},
{
category: 'cooler',
name: 'name4'
}
]
}
];
var mapped = products.map(category => {
return category[Object.keys(category)[0]];
});
var result = [].concat(...mapped); /*<!-- I'm not sure if this is the best implementation (it looks awful).*/
console.log(result);
console.log(result.filter(r => r.name.indexOf("c") > -1 || r.category.indexOf("c") > -1));
修改强>
回应评论。您需要按名称和类别进行过滤:
.filter(p => (p.name.toLowerCase().indexOf(query.toLowerCase()) > -1) || (p.category.toLowerCase().indexOf(query.toLowerCase()) > -1)