使用javascript

时间:2017-01-26 19:27:04

标签: javascript html arrays

我的数据格式如下所示......(示例一)这是一个数组。基于数据,我需要通过自定义条件生成一个html表...比如,表头将是day1,2 ,3,4,5,6及以下数组必须基于每个标题根据条件添加行...我已经提供了详细信息以供参考

 var array=   [{"day":1,"summary":"proge1"},
    {"day":1,"summary":"proge2"},
    {"day":1,"summary":"proge3"},
    {"day":2,"summary":"Tues1"},
    {"day":2,"summary":"Tues2"},
    {"day":2,"summary":"Tues3"},
    {"day":3,"summary":"Wed1"},
    {"day":3,"summary":"Wed2"},
    {"day":3,"summary":"Wed3 "},
    {"day":4,"summary":"Thur1"},
    {"day":4,"summary":"Thur2"},
    {"day":5,"summary":"Fri1"},
    {"day":6,"summary":"Sat1"}]

我想根据这些数据生成一个html表格,以便它显示如下..有人请建议我如何完成这个...

    <table>
     <tr>
                       <td align="center">Day1</td>
                        <td align="center">Day2</td>
                        <td align="center">Day3</td>
                        <td align="center">Day4</td>
                        <td align="center">Day5</td>
                        <td align="center"> Day6 </td>
        </tr>
     </table>    

输出:

    ----------------------------------------------
    Day1    |Day2   Day3    Day4    Day5    Day6
   -----------------------------------------------
    proge1  Tue1    Wed1    Thur1   Fri1    Sat1

    proge2  Tue2    Wed2    Thur2       
    proge3  Tue3    Wed3            

我们是否需要为每个td调用函数(day)并按值生成表?

1 个答案:

答案 0 :(得分:0)

因此,您需要具有唯一值的数组:

var  newarray=[];
 array.forEach(function(el){
   for(var depth=0;depth<newarray.length;depth++){
       newarray[pos]=newarray[pos]||[];
       if(!newarray[pos][el.day-1]){//if the day isnt filled, day 1 is at position zero ( thats why -1)
          newarray[pos][el.day-1]=el;
          return;
       }
  }
});

这将创建一个类似于结构的表:

newarray=[
   [{day:1 ...},{day:2}]
   [{day:1}]
];

现在你可以循环播放并构建你的表:

table=newarray.map(function(row){
  var newrow="<tr>";
  newrow+=row.map(function(el){
        return "<td>"+el.summary+"</td>";
  }).join("");
 newrow+="</tr>";
 return newrow;
}).join("");//make string

然后将它附加到你的dom:

 document.body.innerHTML=table;