循环遍历嵌套对象

时间:2019-12-21 17:18:52

标签: javascript node.js angular typescript ngfor

我想遍历嵌套对象。

"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}}有效。 有没有办法获得rating9count9

3 个答案:

答案 0 :(得分:2)

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>   

答案 1 :(得分:0)

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>

答案 2 :(得分:0)

访问嵌套对象数组元素时,首先必须遍历主数组的“电影”。然后,您必须遍历电影对象内部称为“ rate”的嵌套数组,然后才能按以下方式访问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}
}]

修改后的html代码

<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>