te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>javascript - How to create matrix table - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to create matrix table - Stack Overflow

programmeradmin3浏览0评论

I want to create dynamic matrix type data display using java script, html, and jquery which is shown here.

var reservations = [
    {"date":"22-12-2013","MCHC":"22","Pulse rate":"75","weight":"50" },
    {"date":"11-12-2013","CBC":"5"},
    {"date":"11-12-2013","weight":"55"}
];
var tbody = $('#reservations tbody'),
    props = ["date", "MCHC", "CBC", "Pulse rate", "weight"];

$.each(reservations, function(i, reservation) {
  var tr = $('<tr>');
  $.each(props, function(i, prop) {
       $('<td>').html(reservation[prop]).appendTo(tr);  
  });
  tbody.append(tr);
});

The problem is that the code is working properly but it does not display unique data based on date. For example, as shown in the above link "date:11-12-2013" is repeated twice which I don't want. I want to display unique data.

My desired output is:

I want to create dynamic matrix type data display using java script, html, and jquery which is shown here.

var reservations = [
    {"date":"22-12-2013","MCHC":"22","Pulse rate":"75","weight":"50" },
    {"date":"11-12-2013","CBC":"5"},
    {"date":"11-12-2013","weight":"55"}
];
var tbody = $('#reservations tbody'),
    props = ["date", "MCHC", "CBC", "Pulse rate", "weight"];

$.each(reservations, function(i, reservation) {
  var tr = $('<tr>');
  $.each(props, function(i, prop) {
       $('<td>').html(reservation[prop]).appendTo(tr);  
  });
  tbody.append(tr);
});

The problem is that the code is working properly but it does not display unique data based on date. For example, as shown in the above link "date:11-12-2013" is repeated twice which I don't want. I want to display unique data.

My desired output is:

Share Improve this question edited Dec 28, 2013 at 4:55 ApproachingDarknessFish 14.3k8 gold badges41 silver badges81 bronze badges asked Dec 28, 2013 at 4:51 SharvariSharvari 2572 gold badges4 silver badges11 bronze badges 2
  • I wonder how this question got +4 without even a ment. I believe you just have to sort and re-assemble your array before the $.each(...) sequence. – Milche Patern Commented Dec 28, 2013 at 5:23
  • OK, if your array is ALWAYS to be of this kind, meaning, there won't be doubled props within a 'reservation' element, just filter then join apart the date the rest of a 'reservation'. – Milche Patern Commented Dec 28, 2013 at 5:36
Add a ment  | 

4 Answers 4

Reset to default 7

Try this

Live Demo

var reservations = [
    {"date":"22-12-2013","MCHC":"22","Pulse rate":"75","weight":"50" },
    {"date":"11-12-2013","CBC":"5"},
    {"date":"11-12-2013","weight":"55"}
];
var tbody = $('#reservations tbody'),
    props = ["date", "MCHC", "CBC", "Pulse rate", "weight"];
$.each(reservations, function(i, reservation) {
  var trid = reservation["date"];
    if($("#"+trid).length <= 0) {
      var tr = $('<tr>').attr("id",trid);
      $.each(props, function(i, prop) {
        var tdid = prop.replace(/\s/g, '');
        $('<td>').html(reservation[prop]).attr("id",tdid).appendTo(tr);  
      });
      tbody.append(tr);
    }
    else {
      $.each(props, function(i, prop) {
        var tdid = prop.replace(/\s/g, '');
          $("#"+trid).find("td#"+tdid).html(reservation[prop])
      });  
    }
});
var reservations = [{
"date": "22-12-2013",
    "MCHC": "22",
    "Pulse rate": "75",
    "weight": "50"
}, {
"date": "11-12-2013",
    "CBC": "5"
}, {
 "date": "11-12-2013",
    "weight": "55"
}];
var tbody = $('#reservations tbody'),
props = ["date", "MCHC", "CBC", "Pulse rate", "weight"];
$.each(reservations, function (i, reservation) {
//get the date value of the reservation
var tr = $('td:contains("' + reservation.date +'")').closest('tr');
if (tr.length <= 0)
{
     tr = $('<tr>');
}
$.each(props, function (i, prop) {
    var td = tr.children('.' + prop);
    if (td.length <= 0)
    {            $('<td>').html(reservation[prop]).appendTo(tr).addClass(prop.replace(/\s/g, ''));
    } else 
    {
        td.html(reservation[prop]);
    }
});
tbody.append(tr);
});

While this is similar to the response you already have it looks at the fact that Jquery does not like to have multiple elements with the same ID which the previous answer did with the columns.

Another solution would be to organize reservations before you start building the HTML.

You could do that by using a function like:

function uniqueReservation(reservations) {
  var results = [],
      cache = {}, 
      reservation,date;

  for (var i=0;i<reservations.length;i++) {
    reservation = reservations[i];
    date = reservation.date;

    if (!cache[date]) {
      cache[date] = {};
      results.push(cache[date]);
    } else {
        cache[date] = cache[date];
    }


    for (var k in reservation) {
        cache[date][k] = reservation[k];
    }
  }

  console.log('results',results);
  return results;
}


//before you pass reservations to $.each
reservations = uniqueReservation(reservations);

You could probably write this function a few different ways. However, the idea is the same - organize the data structure how you want it and then build up your HTML. Anyway, here is DEMO.

What about trying the below approach with Vanilla JS, I tried to make it simple and clean to be easily understood from the no JQuery fans, though it is getting benefits from the answers above.

var tbody = document.querySelector('#reservations').querySelector('tbody');
var props = ["date", "MCHC", "CBC", "Pulse rate", "weight"];

var reservations = [
    {"date":"22-12-2013","MCHC":"22","Pulse rate":"75","weight":"50" },
    {"date":"11-12-2013","CBC":"5"},
    {"date":"11-12-2013","weight":"55"}
];

var cache = {},
    date;
reservations.forEach(function(reservation, rIndex){
    date = reservation['date'];
    if (!cache[date]) {
      cache[date] = 'yes';
      var tr = tbody.insertRow(rIndex);
      tr.id = 'id'+date;
      props.forEach(function(){tr.insertCell();})
      tbody.appendChild(tr);
    } 
    var row = tbody.querySelector('#id'+date).rowIndex - 1;
    props.forEach(function(prop,pIndex){
       if(reservation[prop]) 
         tbody.rows[row].cells[pIndex].innerHTML=reservation[prop];
    })
});
table { border-collapse: collapse; }
<table id="reservations" border="2px;">
        <thead>
            <tr>
                <th>Date\Mesurment</th><th>MCHC</th><th>CBC</th><th>Pulse rate</th><th>weight</th>
            </tr>
        </thead>
        <tbody>
        </tbody>
  </table>

For those who read from database, most likely there will be no 2 lines with the same date, so simple they can use the below JS code:

reservations.forEach(function(reservation, rIndex){
      var row = tbody.insertRow(rIndex);
      props.forEach(function(prop,pIndex){
        row.insertCell();
        if(reservation[prop]) 
             tbody.rows[rIndex].cells[pIndex].innerHTML=reservation[prop];
    })
});
发布评论

评论列表(0)

  1. 暂无评论