I have 3 observable arrays like below.
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"}]
I am trying to combine these 3 into below result ,
result = [
{
"firstName":"john",
"lastName":"public",
"location":"development",
"department":"sales"
},
{
"firstName":"sam",
"lastName":"smith",
"location":"ny",
"department":"sales"
}
]
To get the desired result, I have used map function on persons observable to give new object array.
this.store<Person>('persons')
.map(function(person){
let p = new personDetail()
p.firstName = person.firstName,
p.lastName = person.lastName
return p;
})
PersonDetail object has firstName, lastName, location and department properties. How do I do a lookup into departments observable and get a matching row for departmentID to get the department name ?
I am new to rxjs library, please let me know if there is a better way to attain the desired result.
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.
This prints to console:
There're two Observables
department$andlocation$that are filtered withfilter()operator to get the only item with matching ID. ThenforkJoin()operator waits until both of them are complete. OperatormergeMap()then reemits the value returned fromforkJoin(). At the end withtoArray()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