如果id匹配,则将JSON渲染到表

时间:2016-06-22 13:33:54

标签: javascript jquery json

我有一个包含5行和2列的表格。每行都有一个ID列,范围从1-5。

我想将JSON数据添加到该表IF中,该数据与该行具有匹配的ID。如果没有数据与该行ID匹配,则将“无匹配记录”添加到该行的第二列。

Rendered Table

HTML表格

<table class="table table-striped">
    <thead>
      <tr>
        <th>ID</th>
        <th>Lastname</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>1</td>
        <td></td>
      </tr>
      <tr>
        <td>2</td>
        <td></td>
      </tr>
      <tr>
        <td>3</td>
        <td></td>
      </tr>
      <tr>
        <td>4</td>
        <td></td>
      </tr>
      <tr>
        <td>5</td>
        <td></td>
      </tr>
    </tbody>
</table>

Json数据

{"data":[
    {"id":"1", "lastName":"Doe"},
    {"id":"3", "lastName":"Jones"}
]}

预期结果

<table class="table table-striped">
    <thead>
      <tr>
        <th>ID</th>
        <th>Lastname</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>1</td>
        <td>Doe</td>
      </tr>
      <tr>
        <td>2</td>
        <td>No Matching Record</td>
      </tr>
      <tr>
        <td>3</td>
        <td>Jones</td>
      </tr>
      <tr>
        <td>4</td>
        <td>No Matching Record</td>
      </tr>
      <tr>
        <td>5</td>
        <td>No Matching Record</td>
      </tr>
    </tbody>
</table>

5 个答案:

答案 0 :(得分:1)

您可以使用.each()执行此操作,以循环每个tr,然后使用find()从{td中获取与<{>> ID 相同的数据中的对象1}}。

//Loop each row or tr
$('tbody tr').each(function() {
  //Get text or number from each first td in every row
  var i = $(this).find('td:first').text();
  //Find object from data with this id or current id of td
  var r = data.data.find((e) => e.id == i);
  //Select second td from current row
  var t = $(this).find('td:eq(1)');
  //If Object is found with current id add lastName as text else add dummy text or No Matching Record
  (r != undefined) ? t.text(r.lastName): t.text('No Matching Record');
});

&#13;
&#13;
var data = {"data":[{"id":"1", "lastName":"Doe"},{"id":"3", "lastName":"Jones"}]}

$('tbody tr').each(function() {
  var i = $(this).find('td:first').text();
  var r = data.data.find((e) => e.id == i);
  var t = $(this).find('td:eq(1)');

  (r != undefined) ? t.text(r.lastName): t.text('No Matching Record');
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-striped">
  <thead>
    <tr>
      <th>ID</th>
      <th>Lastname</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td></td>
    </tr>
    <tr>
      <td>2</td>
      <td></td>
    </tr>
    <tr>
      <td>3</td>
      <td></td>
    </tr>
    <tr>
      <td>4</td>
      <td></td>
    </tr>
    <tr>
      <td>5</td>
      <td></td>
    </tr>
  </tbody>
</table>
&#13;
&#13;
&#13;

如果您想按行索引而不是td中的文字进行过滤,则可以使用$(this).index() + 1;,其余内容相同

&#13;
&#13;
var data = {
  "data": [{
    "id": "1",
    "lastName": "Doe"
  }, {
    "id": "3",
    "lastName": "Jones"
  }, ]
}

//Loop each row or tr
$('tbody tr').each(function() {
  //Get index of row
  var i = $(this).index() + 1;
  //Find object from data with this id or current id of td
  var r = data.data.find((e) => e.id == i);
  //Select second td from current row
  var t = $(this).find('td:eq(1)');
  //If Object is found with current id add lastName as text else add dummy text or No Matching Record
  (r != undefined) ? t.text(r.lastName): t.text('No Matching Record');
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-striped">
  <thead>
    <tr>
      <th>ID</th>
      <th>Lastname</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td></td>
    </tr>
    <tr>
      <td>2</td>
      <td></td>
    </tr>
    <tr>
      <td>3</td>
      <td></td>
    </tr>
    <tr>
      <td>4</td>
      <td></td>
    </tr>
    <tr>
      <td>5</td>
      <td></td>
    </tr>
  </tbody>
</table>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

首先,为方便起见,将类添加到两种类型的td中。然后下面的代码应该工作。在这里,我遍历tbody中的所有行,然后搜索json是否找到任何匹配值。如果未找到匹配值,则将默认值(“未找到数据”)放在lastName列中。

<table class="table table-striped">
    <thead>
      <tr>
        <th>ID</th>
        <th>Lastname</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td class="id">1</td>
        <td class="name"></td>
      </tr>
      <tr>
        <td class="id">2</td>
        <td class="name"></td>
      </tr>
      <tr>
        <td class="id">3</td>
        <td class="name"></td>
      </tr>
      <tr>
        <td class="id">4</td>
        <td class="name"></td>
      </tr>
      <tr>
        <td class="id">5</td>
        <td class="name"></td>
      </tr>
    </tbody>
</table>


var json = {"data":[
    {"id":"1", "lastName":"Doe"},
    {"id":"3", "lastName":"Jones"}
]};

$(".table tbody tr").each(function(index){
  var curId = $(this).find(".id").text();
  var nameField = "No data found";

  for( var i = 0; i < json.data.length; i++ )
  {
    var row = json.data[i];
    if( row.id == curId )
    {
      nameField = row.lastName;
      return false;
    }
  }

  $(this).find(".name").text( nameField );
});//each

答案 2 :(得分:0)

以下代码可以解决问题:

var response = {"data":[
    {"id":"1", "lastName":"Doe"},
    {"id":"3", "lastName":"Jones"}
]};

var myData = response.data;

var rows = $('#myDataTable tbody tr');
var cells, index, itemFound = false;

rows.each(function (index) {
   cells = $(this).find('td');
   itemFound = false
   for (index=myData.length-1 ; index>= 0 && !itemFound; index--) {
     if (cells.eq(0).text() == myData[index].id) {
       itemFound = true;
       cells.eq(1).text(myData[index].lastName);
       myData.splice(index, 1);
     }
   }
   if (!itemFound) {
     cells.eq(1).text('No matching record');
   }
});

看我工作的小提琴: https://jsfiddle.net/gkptnnxe/

答案 3 :(得分:0)

如果您不想在课程中添加课程或身份证,那么您可以使用此功能。

&#13;
&#13;
var obj = {"data":[
    {"id":"1", "lastName":"Doe"},
    {"id":"3", "lastName":"Jones"}
]};
var trs = document.getElementsByTagName("tr");
// don't need for i==0
for(var i=1; i<trs.length; i++){
  var tds = trs[i].children;
  var id = tds[0].innerHTML;
  var nameFound = false;
  //search this id in json.
  var len = obj.data.length;
  for(var j=0; j<obj.data.length; j++){
    if(obj.data[j].id == id){
      // If found then change the value of this lastName cell.
      tds[1].innerHTML = obj.data[j].lastName;
      nameFound = true;
     }
  }
  // If id is not found is json then set the default message.
   if(nameFound == false){
     tds[1].innerHTML = "No mathcing records";
   }
}
&#13;
<table class="table table-striped">
    <thead>
      <tr>
        <th>ID</th>
        <th>Lastname</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>1</td>
        <td></td>
      </tr>
      <tr>
        <td>2</td>
        <td></td>
      </tr>
      <tr>
        <td>3</td>
        <td></td>
      </tr>
      <tr>
        <td>4</td>
        <td></td>
      </tr>
      <tr>
        <td>5</td>
        <td></td>
      </tr>
    </tbody>
</table>
&#13;
&#13;
&#13;

答案 4 :(得分:0)

您可以td获取index并查看td的text是否匹配将名称添加到下一个td

var data = {
            "data": [
             { "id": "1", "lastName": "Doe" },
             { "id": "3", "lastName": "Jones" }
            ]
        };

            $(".table-striped tbody tr").each(function(){
                var index = data.data.map(function (e) { return e.id }).indexOf($(this).first().text().trim());
                if(index > -1)
                    $(this).children('td:eq(1)').text(data.data[index].lastName);
                else
                    $(this).children('td:eq(1)').text('No matching record');

            });