[json] How to loop through a JSON object with typescript (Angular2)

I am new to Angular2 and I am trying to loop through a JSON object that I am getting back from a GET request but can't work it out.

My JSON object:

{
    Results: [{
        Time: "2017-02-11T08:15:01.000+00:00",
        Id: "data-mopdsjkajskda",
        AuthorId: "58fSDNJD"
    }, {
        Time: "2017-03-11T06:23:34.000+00:00",
        Id: "data-2371212hjb1",
        AuthorId: "43555HHHJ"
    }, {
        Time: "2017-04-11T07:05:11.000+00:00",
        Id: "data-kjskdha22112",
        AuthorId: "XDSJKJSDH"
    }]
}

Part of my Angular script:

interface res {
    Time: string;
    Id: string;
    AuthorId: string;
}
export class AppComponent {
    results: res;
    constructor(private _httpservice: HTTPService) {}
    this._httpservice.getQuery().subscribe(
        data => {
            this.results = data.Results
        },
        error => console.log(error),
        () => console.log('Done')
    );
}

I do get the data back - which is great. However, I want to push the Ids into an array. In Javascript I would do this:

var ids = [];

for (i = 0; i < data.Results.length; i++) {
    ids.push(data.Results[i].Id)
}

The array after the push:

ids = ['data-mopdsjkajskda', 'data-2371212hjb1', 'data-kjskdha22112'];

I am struggling to find a way to achieve the same results with Angular2. Any help would be greatly appreciated!

This question is related to json angular typescript

The answer is


Assuming your json object from your GET request looks like the one you posted above simply do:

let list: string[] = [];

json.Results.forEach(element => {
    list.push(element.Id);
});

Or am I missing something that prevents you from doing it this way?


ECMAScript 6 introduced the let statement. You can use it in a for statement.

var ids:string = [];

for(let result of this.results){
   ids.push(result.Id);
}

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

Examples related to typescript

TS1086: An accessor cannot be declared in ambient context Element implicitly has an 'any' type because expression of type 'string' can't be used to index Angular @ViewChild() error: Expected 2 arguments, but got 1 Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; } Understanding esModuleInterop in tsconfig file How can I solve the error 'TS2532: Object is possibly 'undefined'? Typescript: Type 'string | undefined' is not assignable to type 'string' Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740] Can't perform a React state update on an unmounted component TypeScript and React - children type?