如何使用打字稿(Angular2)循环遍历 JSON 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43726218/
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:51:34  来源:igfitidea点击:

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

jsonangulartypescript

提问by AlexisP

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.

我是 Angular2 的新手,我正在尝试遍历我从 GET 请求中返回的 JSON 对象,但无法解决。

My JSON object:

我的 JSON 对象:

{
    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:

我的 Angular 脚本的一部分:

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:

我确实取回了数据 - 这很棒。但是,我想将 Id 推送到一个数组中。在 Javascript 中,我会这样做:

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!

我正在努力寻找一种方法来实现与 Angular2 相同的结果。任何帮助将不胜感激!

回答by csim

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

假设您的 GET 请求中的 json 对象看起来像您上面发布的那个,只需执行以下操作:

let list: string[] = [];

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

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

还是我错过了阻止你这样做的东西?

回答by Md Ayub Ali Sarker

ECMAScript 6 introduced the letstatement. You can use it in a forstatement.

ECMAScript 6 引入了该let语句。您可以在for语句中使用它。

var ids:string = [];

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