How to skip a JSON object using typescript (Angular2)

I am new to Angular2, and I am trying to go through a JSON object that I am returning from a GET request but cannot handle it.

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 get the data back - it's great. However, I want the Ids to be an array. In Javascript, I would do the following:

var ids = [];

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

Array after clicking:

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

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

+9
source share
2 answers

Assuming your json object from your GET request is similar to the one you posted above, just do:

let list: string[] = [];

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

-, ?

+14

ECMAScript 6 let. for .

var ids:string = [];

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

Source: https://habr.com/ru/post/1676086/


All Articles