问题描述
- js将json格式的'cm',通过循环或其他方式生成'col'
-
// js将json格式的'cm',通过循环或其他方式生成'col'。 (不拼接字符串)var cm = '[{"1":"S", "2":"M", "3":"L"}, {"1":"23", "2":"24"}, {"1":"28", "2":"29", "3":"30"}, {"1":"B28", "2":"B29", "3":"B30"}]'; var col = [ { display: 'S', columns: [{ display: '23', columns: [{display: '28', columns: [{ display: 'B28', name: 'ContactName', width: 100, align: 'left'}] }] }] }, { display: 'M', columns: [{ display: '24', columns: [{display: '29', columns: [{ display: 'B29', name: 'ContactName', width: 100, align: 'left'}] }] }] }, { display: 'L', columns: [{ display: '', columns: [{display: '30', columns: [{ display: 'B30', name: 'ContactName', width: 100, align: 'left'}] }] }] } ];
解决方案
<body>
<div id='testShow'></div>
<script>
var cm = '[{"1":"S", "2":"M", "3":"L"}, {"1":"23", "2":"24"}, {"1":"28", "2":"29", "3":"30"}, {"1":"B28", "2":"B29", "3":"B30"}]';
var cmJSON = JSON.parse(cm);
var col = new Array(3);
var colObj=new Array(3);
for(var i=0;i<cmJSON.length;i++){
for(var j=0;j<col.length;j++){
var value = cmJSON[i][(j+1)+""]?cmJSON[i][(j+1)+""]:"";
if(!col[j]) {
col[j]={};
colObj[j]=col[j];
}else{
colObj[j]['columns']=[{}];
colObj[j]= colObj[j]['columns'][0];
}
colObj[j]['display'] = value ;
if(i==cmJSON.length-1){
colObj[j]['name']= 'ContactName';
colObj[j]['width']= 100;
colObj[j]['align']='left';
}
}
}
colObj.length=0;
document.getElementById('testShow').innerHTML=JSON.stringify(col);
</script>
</body>
时间: 2024-09-18 21:36:24