将json对象转换为typescript中的类类型数组时出错

时间:2017-07-25 07:00:33

标签: javascript arrays json angular

我从服务获取json对象,我想迭代到这个json对象并填充类类型的数组。 以下是调用服务的代码

 public GetMapData(): Observable<Response> {
    var path = 'http://my.blog.net/blog.php?type=trendingDestiny';



    return this.http.get(path)
        .map((response: Response) => {
            if (response.status === 204) {
                return undefined;
            } else {
                return response.json();
            }
        });

}
self.blogapi.GetMapData().subscribe(
        x => {
            this.MapData = x;
            console.log("MapData", this.MapData);
        });

以下是json回复

[
{
    "post_id": 77,
    "post_title": "Delhi",
    "post_content": "DelhiDelhiDelhi",
    "post_date": "2017-07-24 11:47:08",
    "imageurl": false,
    "cat_name": [
        {
            "term_id": 7,
            "name": "FOODIE",
            "slug": "foodie",               
            "category_parent": 0
        }
    ],
    "longitude": "75.857849",
    "latitude": "33.888586",
    "region_name": "Asia"
},
{
    "post_id": 75,
    "post_title": "Goa",
    "post_content": "this is goa",
    "post_date": "2017-07-24 11:03:59",
    "imageurl": false,
    "cat_name": [
        {
            "term_id": 7,
            "name": "FOODIE",
            "slug": "foodie",               
            "category_parent": 0
        }
    ],
    "longitude": "75.857849",
    "latitude": "33.888586",
    "region_name": "Asia"
}]

以下是打字稿代码

this.MapData.forEach(map => {
        this.Mapdatalist.push({
            postid: map.post_id,
            regionname: map.region_name,
            longitude: map.longitude

        });
    });

或者我也试过

for (let data of this.MapData)
    {
        console.log("error",data);

    }

但没有任何作用。它给了我错误

  

错误类型错误:无法读取属性&#39; forEach&#39;未定义的

请帮助出错。

2 个答案:

答案 0 :(得分:0)

var array= [
{
    "post_id": 77,
    "post_title": "Delhi",
    "post_content": "DelhiDelhiDelhi",
    "post_date": "2017-07-24 11:47:08",
    "imageurl": false,
    "cat_name": [
        {
            "term_id": 7,
            "name": "FOODIE",
            "slug": "foodie",               
            "category_parent": 0
        }
    ],
    "longitude": "75.857849",
    "latitude": "33.888586",
    "region_name": "Asia"
},
{
    "post_id": 75,
    "post_title": "Goa",
    "post_content": "this is goa",
    "post_date": "2017-07-24 11:03:59",
    "imageurl": false,
    "cat_name": [
        {
            "term_id": 7,
            "name": "FOODIE",
            "slug": "foodie",               
            "category_parent": 0
        }
    ],
    "longitude": "75.857849",
    "latitude": "33.888586",
    "region_name": "Asia"
}];
//console.log(array);
var mapdata = [];
$.each(array,function(i,v){
 mapdata.push({"postid":v.post_id,"regionname":v.region_name,"longitude":v.longitude});
})
console.log(mapdata);

答案 1 :(得分:0)

请检查您是否已将响应分配给&#34; this.MapData&#34;。我创建了相同的场景,它正在工作。可能是&#34; this.MapData&#34;未正确声明和定义。