js实现json数据行到列的转换
2012-12-24 16:17:17 来源:WEB开发网为了实现这样的数据显示出来三个序列,分别为郑州、新乡、安阳的电量,就需要自己实现对这样数据的转换,转换成如下的形式:
月份 郑州-电量 新乡-电量 安阳-电量
201201 33 29 23
201202 35 26 25
201203 34 27 24
201204 36 28 26
201205 34.3 28.8 24.3
这样,Ext的图表就能把它显示成三个序列了。
我写了如下的函数实现这个功能:
function CovertData(jsonData,idField, fromField, toField){
var result = [], curRecord =null, num;
var fromFields = fromField.split(',');
// 循环整个数组:[{...},{...},{...},...]
for(var idx=0;idx<jsonData.length;idx++){
num = findIdx(result, idField, jsonData[idx][idField]);
if(num!=-1){
curRecord = result[num];
}
else{
curRecord = {};
};
// 循环每个json对象中的字段
for(var key in jsonData[idx]){
// 处理转换的数据内容
for(var i=0;i<fromFields.length;i++){
if(key == fromFields[i]){
curRecord[jsonData[idx][toField]+'-' + fromFields[i]] = jsonData[idx][key];
break;
}
}
// 除数据内容外,只处理标识字段数据
if(key == idField){
curRecord[key] = jsonData[idx][key];
}
}
if(num==-1){
result.push(curRecord);
}
}
return result;
}
function findIdx(jsonData, columnName, value){
for(var idx = 0;idx<jsonData.length;idx++){
if(jsonData[idx][columnName]==value)
return idx;
}
return -1;
}
JsTestDriver的测试代码如下:
TestCase("Test json data row to column",{
setUp:function(){
this.jsonData = [{yearmonth:201201,ppq:23,spq:27,company:'dfsoft'},
{yearmonth:201202,ppq:33,spq:38,company:'dfsoft'},
{yearmonth:201203,ppq:43,spq:49,company:'dfsoft'},
{yearmonth:201204,ppq:53,spq:51,company:'dfsoft'},
{yearmonth:201201,ppq:29,spq:26,company:'vcom'},
{yearmonth:201202,ppq:34,spq:38,company:'vcom'},
{yearmonth:201203,ppq:48,spq:43,company:'vcom'},
{yearmonth:201204,ppq:52,spq:59,company:'vcom'}];
var fromField = 'ppq,spq', toField = 'company', idField = 'yearmonth';
this.resultData = CovertData(this.jsonData,idField,fromField, toField);
},
"test store has columns":function(){
var month1 = this.resultData[findIdx(this.resultData,'yearmonth',201201)];
var month2 = this.resultData[findIdx(this.resultData,'yearmonth',201202)];
var month3 = this.resultData[findIdx(this.resultData,'yearmonth',201203)];
var month4 = this.resultData[findIdx(this.resultData,'yearmonth',201204)];
assertEquals(4,this.resultData.length);
赞助商链接