我在'/ posts /'下有一个帖子列表,我已经检索了所有帖子并将其存储在数组all_posts中:
get_all_posts(){
this.all_posts = [];
firebase.database().ref('/posts/').once('value').then(snapshot => {
foreach.snapshot{
let tmp_data = {
post_id: snapshot.key,
title: snapshot.val().title,
type: snapshot.val().type,
}
this.all_posts.push(tmp_data);
}
}
现在,我想通过单击按钮来过滤类型为“ news”(有2种类型:新闻和博客)的帖子
<ion-button (click)="show_only_posts_type_news()">show only news</ion-button>
show_only_posts_types_news(){
//this.posts
// filter only type == "news"
}
有没有更简单的方法来过滤all_posts?没有另一个Firebase查询以仅显示新闻类型?
答案 0 :(得分:2)
您可以使用Array.filter。您可以提供一个过滤函数,该函数将仅求值并返回那些满足您条件的元素。
var news_posts = this.all_posts.filter(post => post.type === 'news')
答案 1 :(得分:2)
由于您已经遍历快照,因此最好在该循环中进行过滤,而不是再遍历all_posts来获取新闻,然后再获取博客,这可能是array.filter在背景。
get_all_posts(){
this.news_posts = [];
this.blogs_posts = [];
firebase.database().ref('/posts/').once('value').then(snapshot => {
foreach.snapshot{
let tmp_data = {
post_id: snapshot.key,
title: snapshot.val().title,
type: snapshot.val().type,
}
if(tmp_data.type === 'news'
{
this.news_posts(tmp_data)
}
else
{
this.blogs_posts(tmp_data)
}
}
}
答案 2 :(得分:0)
非常感谢@Ashish(对于Array.filter函数,使用了许多方法来过滤数据)。 @Mocas以后我会发布更多类型的帖子,您的方法也可行。
我最终这样做了,该功能可以在单击按钮时过滤帖子类型,不确定是否最好,但是可以按预期工作:
我首先分配了3个数组:
rows = []; //the row that contains displaying data on the view
all_rows = []; //the row that contains all the posts
filtered_rows = []; //the row that contains only filtered posts
过滤功能:
filter_posts_by_type(type){
this.filtered_rows = this.all_rows;
//reset the filtered_rows with all data first
if(type == "news"){
this.rows = this.filtered_rows.filter((item) => {
return item.type.toLowerCase() == "news";
//set this.rows to contain all posts of type : news
})
}else if(type == "blog"){
this.rows = this.filtered_rows.filter((item) => {
return item.type.toLowerCase() == "blog";
//set this.rows to contain all posts of type : blog
})
}else{
// all types
this.rows = this.filtered_rows.filter((item) => {
return item.type.toLowerCase() == "news" || item.type.toLowerCase() == "blog";
//set this.rows to contain all posts types
})
}
}