I want to loop through the the nested object.
"movieRating": {
"rate": [{
"rating9": 9,
"count9": 158
}, {
"rating8": 8,
"count8": 101
}, {
"rating7": 7,
"count7": 32
}, {
"rating6": 6,
"count6": 48
}, {
"rating5": 5,
"count5": 125
}],
"totalCount": 456}
This is my HTML file
<div *ngFor="let movie of movies" class="container">
<table class="table">
<tbody>
<tr >
<th><img src="#"></th>
<td >{{movie.movieRating.rating9}}</td>
</tr>
</tbody>
</table>
</div>
If I try {{movie.movieRating.rating9}}
this is not working. But {{movie.movieRating.totalCount}}
works. Is there a way to get rating9
and count9
.
Rating9
is in position 0 of the rate array, so to access it you can use {{movie.movieRating.rate[0].rating9}}
.
<div *ngFor="let movie of movies" class="container">
<table class="table">
<tbody>
<tr >
<th><img src="#"></th>
<td >{{movie.movieRating.rate[0].rating9}}</td>
</tr>
</tbody>
</table>
</div>
movieRating
has a property called rate
, which is a list of ratings
. So, it would be like movie.movieRating.rate[0].rating9
.
But the HTML part what you have posted in this question will give only one row, that is rating9
's row, then it's no use of looping. So generalise your rate
object like below:
"rate": {
"rating": 9,
"count": 158
}
So It would be very easy to loop also in the future.. like below:
<div *ngFor="let rating of movies.movieRating.rate" class="container">
<table class="table">
<tbody>
<tr >
<th><img src="#"></th>
<td >{{rating}}</td>
</tr>
</tbody>
</table>
</div>
When accessing nested object array elements, first you have to loop through the main array in your case its "movies". Then you have to loop through the nested array called "rate" inside the movie object then you can access the rate values as follows.
Your nested array.
movies:[{
"movieRating": {
"rate": [{
"rating9": 9,
"count9": 158
}, {
"rating8": 8,
"count8": 101
}, {
"rating7": 7,
"count7": 32
}, {
"rating6": 6,
"count6": 48
}, {
"rating5": 5,
"count5": 125
}],
"totalCount": 456}
}]
Modified html code
<div *ngFor="let movie of movies" class="container">
<table class="table">
<tbody>
<tr *ngFor="let rate of movie.movieRating.rate" >
<th><img src="#"></th>
<td >{{movie.movieRating.rating9}}</td>
</tr>
</tbody>
</table>
</div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.