SoFunction
Updated on 2025-04-03

JS instance code to implement json data row to column conversion


function CovertData(jsonData,idField, fromField, toField){
var result = [], curRecord =null, num;
var fromFields = (',');
// Loop the entire array: [{...},{...},{...},...]
for(var idx=0;idx<;idx++){
num = findIdx(result, idField, jsonData[idx][idField]);
if(num!=-1){
curRecord = result[num];
}
else{
curRecord = {};
};
// Loop the fields in each json object
for(var key in jsonData[idx]){
// Process the converted data content
for(var i=0;i<;i++){
if(key == fromFields[i]){
curRecord[jsonData[idx][toField]+'-' + fromFields[i]] = jsonData[idx][key];
break;
}
}
// Except for data content, only identification field data is processed
if(key == idField){
curRecord[key] = jsonData[idx][key];
}
}
if(num==-1){
(curRecord);
}
}
return result;
}

function findIdx(jsonData, columnName, value){
for(var idx = 0;idx<;idx++){
if(jsonData[idx][columnName]==value)
return idx;
}
return -1;
}
The test code of JsTestDriver is as follows:
TestCase("Test json data row to column",{
setUp:function(){
= [{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';
= CovertData(,idField,fromField, toField);
},
"test store has columns":function(){
var month1 = [findIdx(,'yearmonth',201201)];
var month2 = [findIdx(,'yearmonth',201202)];
var month3 = [findIdx(,'yearmonth',201203)];
var month4 = [findIdx(,'yearmonth',201204)];

assertEquals(4,);
assertEquals('23',month1['dfsoft-ppq']);
assertEquals('29',month1['vcom-ppq']);
assertEquals('33',month2['dfsoft-ppq']);
assertEquals('34',month2['vcom-ppq']);
assertEquals('43',month3['dfsoft-ppq']);
assertEquals('48',month3['vcom-ppq']);
assertEquals('53',month4['dfsoft-ppq']);
assertEquals('52',month4['vcom-ppq']);

assertEquals('27',month1['dfsoft-spq']);
assertEquals('26',month1['vcom-spq']);
assertEquals('38',month2['dfsoft-spq']);
assertEquals('38',month2['vcom-spq']);
assertEquals('49',month3['dfsoft-spq']);
assertEquals('43',month3['vcom-spq']);
assertEquals('51',month4['dfsoft-spq']);
assertEquals('59',month4['vcom-spq']);
}
})