我想遍历嵌套对象。
"movieRating": {
"rate": [{
"rating9": 9,
"count9": 158
}, {
"rating8": 8,
"count8": 101
}, {
"rating7": 7,
"count7": 32
}, {
"rating6": 6,
"count6": 48
}, {
"rating5": 5,
"count5": 125
}],
"totalCount": 456}
这是我的 HTML 文件
<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>
如果我尝试{{movie.movieRating.rating9}}
这是行不通的。 但{{movie.movieRating.totalCount}}
有效。 有没有办法得到rating9
和count9
.
Rating9
位于速率数组的位置 0,因此要访问它,您可以使用{{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
有一个名为rate
的属性,它是ratings
的列表。所以,它会像movie.movieRating.rate[0].rating9
.
但是您在此问题中发布的HTML部分只会给出一行,即rating9
行,那么循环就没有用了。因此,概括您的rate
对象如下所示:
"rate": {
"rating": 9,
"count": 158
}
所以将来也很容易循环......如下所示:
<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>
访问嵌套对象数组元素时,首先您必须遍历主数组,在这种情况下是它的"电影"。然后,您必须遍历电影对象中名为"rate"的嵌套数组,然后您可以按如下方式访问速率值。
您的嵌套数组。
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}
}]
修改后的网页代码
<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>