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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39308423/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:36:21  来源:igfitidea点击:

How to convert JSON object to an Typescript array?

arraysjsonangular

提问by GaborH

I have an API request which returns the following:

我有一个 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
    },

I would like to show the fetched movie title after the button click with the following code:

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

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();

      });
  }

}

My problem is that I get an error message which says I can only loop through Arrays, and my data is an Object. How can I convert my Object to Array in typescript, and show the title of the movie in the the table?

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

回答by martin

That's correct, your response is an object with fields:

没错,您的响应是一个带有字段的对象:

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

So you in fact want to iterate the resultsfield only:

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

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

... or even easier:

... 甚至更简单:

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

回答by rahulnikhare

To convert any JSON to array, use the below code:

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

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

回答by rorschach

You have a JSON object that contains an Array. You need to access the array results. Change your code to:

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

this.data = res.json().results