如何将JSON对象转换为TypeScript数组?

21

我有一个API请求,返回以下内容:

{"page": 1,
  "results": [
    {
      "poster_path": "/9O7gLzmreU0nGkIB6K3BsJbzvNv.jpg",
      "adult": false,
      "overview": "Framed in the 1940s for the double murder of his wife and her lover, upstanding banker Andy Dufresne begins a new life at the Shawshank prison, where he puts his accounting skills to work for an amoral warden. During his long stretch in prison, Dufresne comes to be admired by the other inmates -- including an older prisoner named Red -- for his integrity and unquenchable sense of hope.",
      "release_date": "1994-09-10",
      "genre_ids": [
        18,
        80
      ],
      "id": 278,
      "original_title": "The Shawshank Redemption",
      "original_language": "en",
      "title": "The Shawshank Redemption",
      "backdrop_path": "/xBKGJQsAIeweesB79KC89FpBrVr.jpg",
      "popularity": 5.446135,
      "vote_count": 5250,
      "video": false,
      "vote_average": 8.32
    },
    {
      "poster_path": "/lIv1QinFqz4dlp5U4lQ6HaiskOZ.jpg",
      "adult": false,
      "overview": "Under the direction of a ruthless instructor, a talented young drummer begins to pursue perfection at any cost, even his humanity.",
      "release_date": "2014-10-10",
      "genre_ids": [
        18,
        10402
      ],
      "id": 244786,
      "original_title": "Whiplash",
      "original_language": "en",
      "title": "Whiplash",
      "backdrop_path": "/6bbZ6XyvgfjhQwbplnUh1LSj1ky.jpg",
      "popularity": 9.001948,
      "vote_count": 2072,
      "video": false,
      "vote_average": 8.28
    },

我想用以下代码在按钮点击后显示获取到的电影标题:

import {Component} from '@angular/core';
import {Http, Response} from '@angular/http';

@Component({
  selector: 'http',
  template: `

<button (click)="makeRequest()">Make Request</button>

<table class="table table-striped">
      <thead>
        <tr>
          <th>Title</th>
         </tr>
      </thead>

        <tbody>
        <tr *ngFor="let movie of data">
          <td>{{movie.title}}</td>
        </tr>

      </tbody>
    </table>
`
})
export class AppComponent {

  data: Object;

  constructor(public http: Http) {
  }
  makeRequest(): void {

    this.http.request('http://api.themoviedb.org/3/movie/top_rated?api_key=API-KEY')
      .subscribe((res: Response) => {
        this.data = res.json();

      });
  }

}

我的问题是,我收到一个错误消息,提示我只能循环遍历数组,而我的数据是一个对象。 在Typescript中如何将我的对象转换为数组,并在表格中显示电影的标题?

3个回答

21

要将任何JSON转换为数组,请使用以下代码:

const usersJson: any[] = Array.of(res.json());

18

没错,你的回复是一个带有字段的对象:

{
    "page": 1,
    "results": [ ... ]
}

因此,您实际上只想迭代results字段:

this.data = res.json()['results'];

...或者更简单的方法:

this.data = res.json().results;

4

您有一个包含数组的JSON对象。您需要访问数组 results。将您的代码更改为:

this.data = res.json().results

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接