如何在JQuery中将JSON数据转换为Array?

时间:2015-08-24 10:32:30

标签: javascript jquery json

我从结果中获取Json数据如下,

   var chartData1 = [
     {\"Action\":\"Twitter\",\"value\":\"1.00\",\"platform\":\"2\"},
     {\"Action\":\"WhatsApp\",\"value\":\"1.00\",\"platform\":\"3\"},
     {\"Action\":\"Messaging\",\"value\":\"1.00\",\"platform\":\"4\"}
     ]

我想将其转换为以下内容,

   var chartData2 =  [
    ['Action', 'value', 'platform'],
    ['Twitter', '1.00', 2],
    ['WhatsApp', '1.00', 3],
    ['Messaging', 'WhatsApp', 4],
   ]

我使用了不同的方法,如parseJSON,map等,但我无法获得预期的结果。

Can you help me out from this.

3 个答案:

答案 0 :(得分:1)

我假设您首先需要解析包含数据的有效JSON字符串,然后将每个对象转换为数组。并使用列名称在数组前面添加整个数组。以下代码将完全这样做:

var chartDataString = "[{\"Action\":\"Twitter\",\"value\":\"1.00\",\"platform\":\"2\"},{\"Action\":\"WhatsApp\",\"value\":\"1.00\",\"platform\":\"3\"},{\"Action\":\"Messaging\",\"value\":\"1.00\",\"platform\":\"4\"}]";

var chartData = JSON.parse(chartDataString);

var keys = [];
var data = [];
var row;
for (var i = 0; i < chartData.length; i++) {
    row = [];
    for (var key in chartData[i]) {
        if (i === 0) {
            keys.push(key);   
        }

        row.push(chartData[i][key]);
    }

    if (i === 0) {
        data.push(keys);   
    }

    data.push(row);
}

console.log(data);

答案 1 :(得分:0)

以下内容将其转换为数组,前提是它已被解析为对象。

var chartData2 = Object.keys(chartData1).map(function(k) { return chartData1[k] });

console.log(chartData2);

答案 2 :(得分:0)

这里最理想的可能是将原始数组映射到新结构:

var chartData1 = [
     {"Action":"Twitter","value":"1.00","platform":"2"},
     {"Action":"WhatsApp","value":"1.00","platform":"3"},
     {"Action":"Messaging","value":"1.00","platform":"4"}
];

var result = chartData1.map(function(el) {
    return [el.Action, el.value, el.platform];
});
result.unshift(['Action', 'value', 'platform']);


alert(JSON.stringify(result, null, 4));