Combine multiple observable arrays into new object array

前端 未结 3 972
感情败类
感情败类 2021-01-14 01:44

I have 3 observable arrays like below.

persons = [
   {
      \"firstName\":\"john\",
      \"lastName\":\"public\",
      \"locationID\":\"1\",
      \"depa         


        
3条回答
  •  余生分开走
    2021-01-14 02:34

    Since you'll very likely want to fetch lists of departments and locations from a remote service (make another HTTP request) I'd do it right away with Observables as well.

    Observable.from(persons)
        .mergeMap(person => {
            let department$ = Observable.from(departments)
                .filter(department => department.departmentID == person.departmentID);
    
            let location$ = Observable.from(locations)
                .filter(location => location.locationID == person.locationID);
    
            return Observable.forkJoin(department$, location$, (department, location) => {
                return {
                    'firstName': person.firstName,
                    'lastName': person.lastName,
                    'location': location.name,
                    'department': department.name,
                };
            });
        })
        .toArray()
        .subscribe(result => console.log(result));
    

    This prints to console:

    [ { firstName: 'john',
        lastName: 'public',
        location: 'chicago',
        department: 'development' },
      { firstName: 'sam',
        lastName: 'smith',
        location: 'ny',
        department: 'sales' } ]
    

    There're two Observables department$ and location$ that are filtered with filter() operator to get the only item with matching ID. Then forkJoin() operator waits until both of them are complete. Operator mergeMap() then reemits the value returned from forkJoin(). At the end with toArray() we collect all items into a single array.

    Instead of Observable.from(...) you can have whatever service you'll need (eg. http.get(...)).

    See live demo: https://jsbin.com/nenekup/4/edit?js,console

    Similar questions: Merge subarrays using Observables and Subscribing to a nested Observable

提交回复
热议问题