18

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!

AlexisP
  • 399
  • 4
  • 6
  • 16
  • This should be Javasript question. Angular has nothing to do with for loop. Anyway, you can use this instead. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach?v=example – wannadream May 01 '17 at 20:51
  • [this](https://stackoverflow.com/a/34913733/11457981) answer helped me well. – Abdu Mar 20 '21 at 07:39

2 Answers2

24

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?

csim
  • 460
  • 4
  • 10
24

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);
}
Michael D
  • 20,838
  • 4
  • 12
  • 37
Md Ayub Ali Sarker
  • 7,364
  • 2
  • 19
  • 18