熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> JSP教程 >> 正文

js實現json數據行到列的轉換

2022-06-13   來源: JSP教程 

  為了實現這樣的數據顯示出來三個序列分別為鄭州新鄉安陽的電量就需要自己實現對這樣數據的轉換轉換成如下的形式

  月份 鄭州電量 新鄉電量 安陽電量

  

  

  

  

  

  這樣Ext的圖表就能把它顯示成三個序列了

  我寫了如下的函數實現這個功能

  function CovertData(jsonDataidField fromField toField){
var result = [] curRecord =null num;
var fromFields = fromFieldsplit();
// 循環整個數組[{}{}{}]
for(var idx=;idx<jsonDatalength;idx++){
num = findIdx(result idField jsonData[idx][idField]);
if(num!=){
curRecord = result[num];
}
else{
curRecord = {};
};
// 循環每個json對象中的字段
for(var key in jsonData[idx]){
// 處理轉換的數據內容
for(var i=;i<fromFieldslength;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==){
resultpush(curRecord);
}
}
return result;
}

function findIdx(jsonData columnName value){
for(var idx = ;idx<jsonDatalength;idx++){
if(jsonData[idx][columnName]==value)
return idx;
}
return ;
}
JsTestDriver的測試代碼如下

  TestCase("Test json data row to column"{
setUp:function(){
thisjsonData = [{yearmonth:ppq:spq:company:dfsoft}
{yearmonth:ppq:spq:company:dfsoft}
{yearmonth:ppq:spq:company:dfsoft}
{yearmonth:ppq:spq:company:dfsoft}
{yearmonth:ppq:spq:company:vcom}
{yearmonth:ppq:spq:company:vcom}
{yearmonth:ppq:spq:company:vcom}
{yearmonth:ppq:spq:company:vcom}];

var fromField = ppqspq toField = company idField = yearmonth;
thisresultData = CovertData(thisjsonDataidFieldfromField toField);
}
"test store has columns":function(){
var month = thisresultData[findIdx(thisresultDatayearmonth)];
var month = thisresultData[findIdx(thisresultDatayearmonth)];
var month = thisresultData[findIdx(thisresultDatayearmonth)];
var month = thisresultData[findIdx(thisresultDatayearmonth)];

assertEquals(thisresultDatalength);
assertEquals(month[dfsoftppq]);
assertEquals(month[vcomppq]);
assertEquals(month[dfsoftppq]);
assertEquals(month[vcomppq]);
assertEquals(month[dfsoftppq]);
assertEquals(month[vcomppq]);
assertEquals(month[dfsoftppq]);
assertEquals(month[vcomppq]);

assertEquals(month[dfsoftspq]);
assertEquals(month[vcomspq]);
assertEquals(month[dfsoftspq]);
assertEquals(month[vcomspq]);
assertEquals(month[dfsoftspq]);
assertEquals(month[vcomspq]);
assertEquals(month[dfsoftspq]);
assertEquals(month[vcomspq]);
}
})
測試通過表示轉換成功


From:http://tw.wingwit.com/Article/program/Java/JSP/201311/20611.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.