将多个可观察数组合并到新对象数组中

You*_*suf 4 javascript rxjs typescript rxjs5 angular

我有3个可观察的数组,如下所示.

persons = [
   {
      "firstName":"john",
      "lastName":"public",
      "locationID":"1",
      "departmentID":"100"
   },
   {
      "firstName":"sam",
      "lastName":"smith",
      "locationID":"2",
      "departmentID":"101"
   }
]

departments = [{"departmentID": "100",
               "name": "development"
               },
               {"departmentID": "101",
                "name": "sales"
               }]

locations = [{"locationID": "1", "name": "chicago"},
              {"locationID":"2", "name": "ny"}]
Run Code Online (Sandbox Code Playgroud)

我试图将这3个结合到下面的结果中,

result = [
   {
      "firstName":"john",
      "lastName":"public",
      "location":"development",
      "department":"sales"
   },
   {
      "firstName":"sam",
      "lastName":"smith",
      "location":"ny",
      "department":"sales"
   }
]
Run Code Online (Sandbox Code Playgroud)

为了得到理想的结果,我在可观察的人身上使用了map函数来给出新的对象数组.

this.store<Person>('persons')
.map(function(person){
     let p = new personDetail()
     p.firstName = person.firstName,
     p.lastName = person.lastName
     return p;
})
Run Code Online (Sandbox Code Playgroud)

PersonDetail对象有firstName,lastName,location和department特性.如何查找可观察的部门并获取匹配的行departmentID以获取部门名称?

我是rxjs库的新手,请告诉我是否有更好的方法来达到预期的效果.

mar*_*tin 7

由于您很可能想要从远程服务获取部门和位置列表(发出另一个HTTP请求),我也会立即使用Observables.

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));
Run Code Online (Sandbox Code Playgroud)

这打印到控制台:

[ { firstName: 'john',
    lastName: 'public',
    location: 'chicago',
    department: 'development' },
  { firstName: 'sam',
    lastName: 'smith',
    location: 'ny',
    department: 'sales' } ]
Run Code Online (Sandbox Code Playgroud)

有两个Observable department$,location$它们被filter()运算符过滤以获得唯一具有匹配ID的项目.然后forkJoin()操作员等待,直到它们都完成.mergeMap()然后,运算符重新发送从中返回的值forkJoin().最后,toArray()我们将所有项目收集到一个数组中.

而不是Observable.from(...)你可以拥有你需要的任何服务(例如http.get(...)).

查看现场演示:https://jsbin.com/nenekup/4/edit?js,console

类似问题:使用Observables和订阅嵌套Observable来合并子阵列