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

I have an API request which returns the following:

{"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?

This question is related to arrays json angular

The answer is


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

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

So you in fact want to iterate the results field only:

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

... or even easier:

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

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

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

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

this.data = res.json().results

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to angular

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class error TS1086: An accessor cannot be declared in an ambient context in Angular 9 TS1086: An accessor cannot be declared in ambient context @angular/material/index.d.ts' is not a module Why powershell does not run Angular commands? error: This is probably not a problem with npm. There is likely additional logging output above Angular @ViewChild() error: Expected 2 arguments, but got 1 Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class' Access blocked by CORS policy: Response to preflight request doesn't pass access control check origin 'http://localhost:4200' has been blocked by CORS policy in Angular7