'Looping through an array and observable in Angular
I have an observable that I am getting back from my service that has a nested array value. I want to push all the class costs out into a new, separate array. How do I go about this?
Student First_name Last_name Class[ Class_name Class_cost ]
The best I can do is
this.classCostData = []
this.classCostData.push(this.students$.subscribe(data => data.map(student => student.class_cost.forEach(class => this.classCostData.push(class.class_cost)))))
When I print the value of that, I get an array, but it says [Safesubscriber] and I cannot access the values
Solution 1:[1]
Your datastructure is a bit unclear for me, however I created an example that should help make things clear.
- First of all: you should use rxjs pipe with map operators. This will help make things much cleaner going forward.
- Second: you should only subscribe if absolutely necessary. (memory leaks & more)
let students$ = of([
{ firstName: "egbert", class: [10, 15, 20] },
{ firstName: "cobal", class: [60, 80] }
]);
students$
.pipe(
map((data) => data.map((student) => student.class)),
map((multiDimArray: number[][]) => [].concat(...multiDimArray))
)
.subscribe((data) => console.log(data));
First in the pipe we map the data to only get the class array. Then we "flatten" the array so we have 1 array with all prices.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Wannes Van Dorpe |
