JS - 将对象转换为数组

时间:2015-07-17 19:07:33

标签: javascript arrays object

我有以下对象数组:

[{"CZ-PR":"1"},{"CZ-JC":"0"},{"CZ-JM":"0"},{"CZ-KA":"0"},{"CZ-VY":"0"},{"CZ-KR":"0"},{"CZ-LI":"0"},{"CZ-MO":"0"},{"CZ-OL":"0"},{"CZ-PA":"0"},{"CZ-PL":"0"},{"CZ-ST":"0"},{"CZ-US":"0"},{"CZ-ZL":"0"}]

我需要将其转换为数组数组,如此(需要将其传递给Google Maps Geocharts构造函数):

[["CZ-PR","1"],["CZ-JC","0"]]

我试过了:

var arr = [];
for (var k in obj) arr.push([+k, obj[k]]);

这给了我每个字母的数组......如何将我的初始对象转换为我需要的?

编辑: Google地理标志所期望的格式为:

var data = google.visualization.arrayToDataTable([
      ['Country', 'Popularity'],
      ['Germany', 200],
      ['United States', 300],
      ['Brazil', 400],
      ['Canada', 500],
      ['France', 600],
      ['RU', 700]
    ]);

2 个答案:

答案 0 :(得分:2)

试试这个

  as.data.frame(table(yourdf$id))

答案 1 :(得分:2)

也许这就是你要找的东西:

var objectArray = [{"CZ-PR":"1"},{"CZ-JC":"0"},{"CZ-JM":"0"},{"CZ-KA":"0"},{"CZ-VY":"0"},{"CZ-KR":"0"},{"CZ-LI":"0"},{"CZ-MO":"0"},{"CZ-OL":"0"},{"CZ-PA":"0"},{"CZ-PL":"0"},{"CZ-ST":"0"},{"CZ-US":"0"},{"CZ-ZL":"0"}];

// build data array
var dataArray = objectArray.map(function(e) { 
    var key = Object.keys(e).pop();
    return [key,e[key]];
});

// add the headers!
dataArray.unshift(['Country', 'Popularity']);

// pass data to google
var data = google.visualization.arrayToDataTable(
    dataArray
);

运气!