2017-08-15 43 views
1

我想了解我的用例的.distinct操作:通過用戶輸入如何使用.distinct通過一個對象屬性的內容從一個數組中刪除對象

我做的是一個國家的搜索並且只想在名爲country的屬性中僅顯示具有特定內容的一個對象。

說明:

我有各種物體的內容的BehaviorSubject:

[ 
{id:1, country: "United Kingdom", city:"London"}, 
{id:2, country: "United Kingdom", city:"Manchester"}, 
{id:3, country: "Germany", city:"Berlin"}, 
... 
] 

類型的陣列的是例如loc[]

interface loc { 
    id: number; 
    country: string; 
    city: string; 
} 

這是過濾通過用戶輸入(在下面的代碼中稱爲「查詢」):

BehaviorSubject 
    .map(x => x.filter((l) => 
    l.country.toLowerCase().indexOf(query.toLowerCase()) > -1)) 

如果用戶輸入是'美國',我得到一個結果數組與兩個對象。

要獲取只有一個對象,我使用另一個.map來處理重複項(標準js代碼以從數組中刪除重複項)並返回一個只包含一個對象的數組。

  1. 如何使用.distinct刪除陣列中的重複項?
  2. 如果你看第.mapx的類型是loc[]。我如何獲得.map運算符中數組的項而不是數組類型?

在此先感謝

回答

0

就像在rxjs一切:這裏有很多方法,如何做到這一點 - 這是我會怎麼做:

關於distinct:如所描述的docs,它帶有一個可選的KeySelectors功能作爲第一個參數,在這裏你可以回報國家:

.distinct(entry => entry.country) 

下面是完整的例子:

const allEntries$ = Rx.Observable.from([ 
 
{id:1, country: "United Kingdom", city:"London"}, 
 
{id:2, country: "United Kingdom", city:"Manchester"}, 
 
{id:3, country: "Germany", city:"Berlin"} 
 
]) 
 
    .publishReplay() 
 
    .refCount(); 
 

 
const userInput$ = new Rx.ReplaySubject(""); 
 
// just for demonstration-purposes 
 
userInput$.subscribe(input => console.log(">> Userinput: " + input)); 
 

 
// this is the important block 
 
const result$ = userInput$ 
 
    .switchMap(input => allEntries$ 
 
    .filter(forCountry(input)) 
 
    .distinct(byCountry) 
 
); 
 

 
// some helper for the filter, you could also do this inline, but it reads better this way 
 
function forCountry(country) { 
 
    country = country || ""; 
 
    coutnry = country.toLowerCase(); 
 
    return entry => entry.country.toLowerCase().indexOf(country) >= 0; 
 
} 
 

 
// some helper for the distinct, you could also do this inline, but it reads better this way 
 
function byCountry(entry) { 
 
    return entry.country; 
 
} 
 

 
// --- Simulation start 
 
result$.subscribe(result => console.log(">>>> Result: " + result.city)); // activate the stream 
 

 
userInput$.next("united"); 
 
userInput$.next("germ"); 
 
userInput$.next("e");
<script src="https://unpkg.com/rxjs/bundles/Rx.min.js"></script>

+0

感謝您的回答。當你有一個BehaviorSubject 而不是Observable.of 時,你將如何處理你的例子? – Mika

+0

這應該沒有區別 - 唯一的一點是,如果BehaviorSubject更改的次數比userInput更快,那麼'distinct'可能會有不同的行爲 - 但是可以通過在當前switchMap中添加和附加級別來修復。 – olsn

相關問題