2015-01-21 82 views
0

我必须使用Highchart在我的项目中创建一个柱状图。我使用$ .ajax来填充这些数据。我现在的JSON数据是这样的:从JSON填充Highchart列

[{ 
    "city": "Tokyo", 
    "totalA": "10", 
    "totalB": "15" 
}, 
{ 
    "city": "Seoul", 
    "totalA": "20", 
    "totalB": "27" 
}, 
{ 
    "city": "New York", 
    "totalA": "29", 
    "totalB": "50" 
}] 

如何产生的JSON字符串是这样的:

[{ 
"name": "city", 
"data": ["Tokyo", "Seoul", "New York"] 
}, { 
"name": "totalA", 
"data": [10, 20, 29] 
}, { 
"name": "totalB", 
"data": [15, 27, 50] 
}] 

谢谢。

+0

将全部数组中的源元素看起来是相同的?他们都会有相同的领域(城市,总数A,总数B) – 2015-01-21 08:08:49

+0

好吧,他们有相同的领域。 – Mkhuda 2015-01-21 09:55:29

回答

1

假设所有的元素看起来都一样(它们都具有相同的字段):Live Example

// src is the source array 
// Get the fields from the first element 
var fields = Object.keys(src[0]); 

// Map each key to... 
var result = fields.map(function(field) { 
    // Grab data from the original source array 
    var data = src.reduce(function(result, el) { 
     // And create an array of data 
     return result.concat(el[field]); 
    }, []); 
    // Format it like you want 
    return {name: field, data: data}; 
}); 

console.log(result); 

如果不是,代码稍微复杂一些:Live Example

// Work out the fields by iterating all of the elements 
// and adding the keys that weren't found yet to an array 
var fields = src.reduce(function (fields, current) { 
    return fields.concat(Object.keys(current).filter(function (key) { 
     return fields.indexOf(key) === -1; 
    })); 
}, []); 

var result = fields.map(function (field) { 
    // Need another step here, filter out the elements 
    // which don't have the field we care about 
    var data = src.filter(function (el) { 
     return !!el[field]; 
    }) 
    // Then continue like in the example above. 
    .reduce(function (result, el) { 
     return result.concat(el[field]); 
    }, []); 
    return { 
     name: field, 
     data: data 
    }; 
}); 

console.log(result);