如何在AngularJS 2中将JSON Http响应转换为Array

时间:2016-11-01 18:07:13

标签: arrays json angular ionic-framework

我正在Angular 2中进行Http get,并且响应是JSON。但是,我试图在ngFor中使用它,但我不能,因为它不是一个数组。

如何在Angular 2中将JSON转换为数组?我在许多网站上搜索过,但没有找到有效的方法。

修改1:

响应是这样的:

{
  "adult": false,
  "backdrop_path": "/fCayJrkfRaCRCTh8GqN30f8oyQF.jpg",
  "belongs_to_collection": null,
  "budget": 63000000,
  "genres": [
    {
      "id": 18,
      "name": "Drama"
    }
  ],
  "homepage": "",
  "id": 550,
  "imdb_id": "tt0137523",
  "original_language": "en",
  "original_title": "Fight Club",
  "overview": "A ticking-time-bomb insomniac and a slippery soap salesman channel primal male aggression into a shocking new form of therapy. Their concept catches on, with underground \"fight clubs\" forming in every town, until an eccentric gets in the way and ignites an out-of-control spiral toward oblivion.",
  "popularity": 0.5,
  "poster_path": null,
  "production_companies": [
    {
      "name": "20th Century Fox",
      "id": 25
    }
  ],
  "production_countries": [
    {
      "iso_3166_1": "US",
      "name": "United States of America"
    }
  ],
  "release_date": "1999-10-12",
  "revenue": 100853753,
  "runtime": 139,
  "spoken_languages": [
    {
      "iso_639_1": "en",
      "name": "English"
    }
  ],
  "status": "Released",
  "tagline": "How much can you know about yourself if you've never been in a fight?",
  "title": "Fight Club",
  "video": false,
  "vote_average": 7.8,
  "vote_count": 3439
}

2 个答案:

答案 0 :(得分:0)

我认为如果你想从json传递给数组,你可以执行以下命令:

var arr = []
for(i in json_object){
   arr.push(i)
   arr.push(json_object[i])
}

然后你有偶数索引中的每个键和奇数索引中的每个内容

答案 1 :(得分:0)

嗯,我真的不明白这一点。数组用于操作类似对象或类型的列表,而不是复杂结构。如果你有一堆类似于你展示的对象,那么它就有意义了。无论如何,如果你真的想要一个数组,那么你可以用递归来创建一个平面数组的属性。

var flatPropertyArray = [];
function flatten(obj) {
    for (var property in obj) {
        if (obj.hasOwnProperty(property)) {
            if (typeof obj[property] == "object")
                flatten(obj[property]);
            else
               flatPropertyArray.push(property);
        }
    }
}

将你的JSON传递给flatten func。