通过解码json创建一个二维数组

时间:2014-06-18 08:04:17

标签: javascript arrays json angularjs

我有以下json:

[ { "location" : { "LocationName" : "Location1",
    "id_Location" : "1"
} },
{ "location" : { "LocationName" : "Location2",
    "id_Location" : "2"
} },
{ "location" : { "LocationName" : "Location3",
    "id_Location" : "3"
} },

我需要解码这个json并创建一个像下面这样的二维数组,

locationArray = [
[{
  LocationName: 'Location1',
  id_Location: '1'
}, {
  LocationName: 'Location2',
  id_Location: '2'
}, {
  LocationName: 'Location3',
  id_Location: '3'
}],
[]
];

我正在使用angular.js,因此使用angular.foreach循环。

2 个答案:

答案 0 :(得分:1)

您可以使用Array.prototype.map功能。

var a =[ { "location" : { "LocationName" : "Location1",
        "id_Location" : "1"
      } },
  { "location" : { "LocationName" : "Location2",
        "id_Location" : "2"
      } },
  { "location" : { "LocationName" : "Location3",
        "id_Location" : "3"
      } }];

var locationArray = a.map(function(o) { return o.location; });

答案 1 :(得分:0)

你可以这样做:

var jsonArr = [];    
angular.forEach(yourJson.location, function(val, iter){
    var actLocation = {locationName: val.LocationName, id_location: val.id_location};
    jsonArr.push(actLocation);
});