Reputation: 1049
I have this response from a http get
{
"parents": [{
"id": 1
, "children": [{
"name": "child1"
}
, {
"name": "child2"
}]
}, {
"id": 2
, "children": [{
"name": "child1"
}]
}]
}
and I have this interface
export interface Child {
parentId: string
, name: string
}
Question
Which map should I do to obtain an array of children (in the response of the subscription), with the name and the id of the parent?
getChildren(): Observable<Child[]> {
return this.http
.get(API_URL)
.//map function;
}
Or at least, tell me where to look to find some sort of answer
Thanks in advance.
Upvotes: 0
Views: 1666
Reputation: 96949
You can use a single map()
operator and then inside it use Array.forEach()
and Array.map()
:
const Observable = Rx.Observable;
data = {
"parents": [{
"id": 1
, "children": [{
"name": "child1"
}
, {
"name": "child2"
}]
}, {
"id": 2
, "children": [{
"name": "child1"
}]
}]
};
Observable.of(data)
.map(data => {
let results = [];
data['parents'].forEach(item => {
results = results.concat(item['children'].map(child => {
return {
'parentId': item.id,
'name': child.name,
};
}));
});
return results;
})
.subscribe(val => console.log(val));
This will print the following (an array containing objects as a single emission):
[ { parentId: 1, name: 'child1' },
{ parentId: 1, name: 'child2' },
{ parentId: 2, name: 'child1' } ]
Upvotes: 1