簡體   English   中英

如何將JSON對象轉換為Typescript數組?

[英]How to convert JSON object to an Typescript array?

我有一個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();

      });
  }

}

我的問題是我收到一條錯誤消息,說我只能循環遍歷數組,而我的數據是一個對象。 如何在打字稿中將我的對象轉換為數組,並在表格中顯示電影的標題?

這是正確的,你的回復是一個帶有字段的對象:

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

所以你實際上只想迭代results字段:

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

......甚至更容易:

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

要將任何JSON轉換為數組,請使用以下代碼:

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

您有一個包含Array的JSON對象。 您需要訪問數組results 將您的代碼更改為:

this.data = res.json().results

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM