gpt4 book ai didi

javascript - 将多个可观察数组组合成新的对象数组

转载 作者:太空狗 更新时间:2023-10-29 17:43:29 25 4
gpt4 key购买 nike

我有 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"}]

我正在尝试将这 3 个组合成下面的结果,

result = [
{
"firstName":"john",
"lastName":"public",
"location":"development",
"department":"sales"
},
{
"firstName":"sam",
"lastName":"smith",
"location":"ny",
"department":"sales"
}
]

为了获得预期的结果,我在 persons observable 上使用了 map 函数来提供新的对象数组。

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

PersonDetail 对象具有 firstNamelastNamelocationdepartment 属性。如何查找可观察的部门并获取 departmentID 的匹配行以获取部门名称?

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

最佳答案

因为您很可能希望从远程服务获取部门和位置列表(发出另一个 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));

这会打印到控制台:

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

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

代替Observable.from(...),您可以获得您需要的任何服务(例如http.get(...))。

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

类似问题:Merge subarrays using ObservablesSubscribing to a nested Observable

关于javascript - 将多个可观察数组组合成新的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41255718/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com