[英]Flatten observable array in Angular2
我在Angular2應用程序中使用Firebase從數據庫中檢索數據。 最簡單的方法是在嵌套標簽列表中返回唯一值數組? 也就是說,在我的示例中,我想返回["Sport", "Adventure", "Music"]
,其中省略了第二個“ Adventure” 。
{
"images": {
"image1": {
"path": "path",
"date": 43534532123,
"tags": {
0: "Sport",
1: "Adventure"
}
},
"image2": {
"path": "path",
"date": 43534532123,
"tags": {
0: "Music",
1: "Adventure"
}
}
}
我嘗試了這種方法,但似乎僅將元素與第一張圖像分開
return this.af.database.list('/photos/user')
.map(photos => photos.map(photo => photo.tags))
.concatAll()
.distinct()
但是,這種方法可以產生正確的輸出,但它是唯一標記的獨立流,而不是一個數組
return this.af.database.list('/photos/user')
.map(photos => photos.map(photo => photo.tags))
.mergeAll()
.mergeAll()
.distinct()
UPDATE
我在原始答案中假設這是單個項目的集合。 后來,OP澄清說這是一張照片清單。 在這種情況下,我們使用Array#reduce
代替Observable#reduce
。
return this.af.database.list('/photos/user')
.map(photos => photos.map(photo => photo.tags)
.reduce((allTags, current) => {
return allTags.concat(
current.filter(item => allTags.indexOf(item) === -1))
}, []))
原始答案
在一個可觀察對象上distinct
,將在流中返回唯一的單個值,但這不是我們想要的運算符。 可能會產生一個包含所有標簽的序列,每個標簽都作為一個單獨的值,但隨后我們需要再次將它們重新分組。
我們可以改為使用reduce
,與Array相當。 它采用初始值( []
)並累加其他值。 我們在每次迭代中構建了一個包含各個值的列表。 減少之后,我們有一個唯一標簽數組。
請注意, .list()
應該完成可觀察項以使其起作用。
return this.af.database.list('/photos/user')
.map(photos => photos.map(photo => photo.tags))
.reduce((allTags, current) => {
return allTags.concat(
current.filter(item => allTags.indexOf(item) === -1))
}, [])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.