将json文件转换为另一种格式

时间:2014-12-04 08:48:44

标签: javascript json

如何将json文件转换为其他格式?我读到了“地图”方法,但不知道如何使用它。

[{"Southern":"9"},{"South-West":"83"},{"South-East":"448"},{"Western":"638"},{"North-Western":"706"},{"Eastern":"710"},{"North-East":"1055"}]

我想转换:

        [
            ['Southern', 9],
            ['South-West', 83],                   
            ['South-East', 448],
            ['Western', 638],
            ['North-Western', 706],
            ['Eastern', 710],
            ['North-East', 1055],

        ]

代码:

 data.map(function(e) {
    ..........
    });

2 个答案:

答案 0 :(得分:4)

newData = data.map(function(e) {
    var key = Object.keys(e)[0];
    return [ key, parseInt(e[key], 10) ];
});

但是,如果将它转换为单个对象,它似乎会更有用:

{ 
    'Southern': 9,
    'South-West': 83,
    'South-East': 448,
    'Western': 638,
    'North-Western': 706
    'Eastern': 710
    'North-East': 1055
}

这可以通过以下方式完成:

newObject = {};
data.forEach(function(e) {
    var key = Object.keys(e)[0];
    newObject[key] = e[key];
});

答案 1 :(得分:1)

如果您不想使用地图,可以使用简单的循环:

var result = [];
for (var i = 0, l = arr.length; i < l; i++) {
  var key = Object.keys(arr[i])[0];
  var val = parseInt(arr[i][key], 10);
  result.push([key, val])
}

DEMO