Convert HTML Rows into Name Value Pair in JQuery

﹥>﹥吖頭↗ 提交于 2021-01-28 20:49:27

问题


I am trying to convert an HTML Table to Name-Value pair in JSON format using Jquery.

 <table class="table">
        <thead class="thead-light">
           <tr>
                  <th>MobileNumber</th>
                   <th>Amount</th>
                   <th>Fuel</th>
            </tr>
          </thead>
          <tbody>
              <tr>
                  <td>1223445</td>
                  <td>12.49</td>
                  <td>1223</td>
              </tr>
              <tr>
                  <td>99999</td>
                  <td>11.39</td>
                  <td>1277745</td> 
              </tr>
          </tbody>
      </table>

The above table should get converted to a JSON formatted name value pair as below

[{
       "Customer":{ 
          "MobileNumber":"1223445"
        },
        "TemplateFieds": [{
           "Name": "Amount",
           "value": "12.49"
         },
         {
            "Name":"Fuel",
             "value": "1223"
         }]
  },
  {
       "Customer":{ 
          "MobileNumber":"99999"
        },
        "TemplateFieds": [{
           "Name": "Amount",
           "value": "11.39"
         },
         {
            "Name":"Fuel",
             "value": "1277745"
         }]
  }]

I am trying to modify this function from (get values from table as key value pairs with jquery) but I cant get it right.

  var result = $('myTable tbody').children().map(function () {
               var children = $(this).children();
                return {
                    name: children.eq(0).text(),
                    value: children.eq(1).text()
                };
               }).get();

Anyone has idea to convert the HTML table to above mentioned JSON format?

-Alan-


回答1:


You can simply select the column names from the <th> elements as well and match them via the column index. I also fixed your "TemplateFieds" typo, which should be "TemplateFields". (missing "l")

var colNames = $('.table thead th').get().map(el => el.textContent);
var result = $('.table tbody').children().map(function() {
  var children = $(this).children().get();
  var resultObj = {Customer: {}, TemplateFields: []};
  children.forEach((cell, index) => {
    if (index === 0) {
      resultObj['Customer'][colNames[index]] = cell.innerText;
    } else {
      resultObj['TemplateFields'].push({
        name: colNames[index],
        value: cell.innerText
      });
    }
  });
  return resultObj;
}).get();
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table">
  <thead class="thead-light">
    <tr>
      <th>MobileNumber</th>
      <th>Amount</th>
      <th>Fuel</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1223445</td>
      <td>12.49</td>
      <td>1223</td>
    </tr>
    <tr>
      <td>99999</td>
      <td>11.39</td>
      <td>1277745</td>
    </tr>
  </tbody>
</table>



回答2:


First, loop through the thead to get the Name properties:

var cols = $("table>thead>tr>th").map(function() {
  return $(this).text()
});

then loop through each row $('table>tbody>tr') creating an entry to add to your result array and within each row, loop through each cell except the first to generate the name/value pair.

var cols = $("table>thead>tr>th").map(function() {
  return $(this).text()
});

var result = [];

$('table>tbody>tr').each(function() {
  var cells = $(this).find("td");
  var row = {
    Customer: { MobileNumber: cells.first().text() },
    TemplateFieds: []
  };
  cells.each(function(i, e) {
    if (i == 0) return; // skip first col
    row.TemplateFieds.push({
      "Name": cols[i],
      "value": $(this).text()
    })
  });
  result.push(row);
});

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table">
  <thead class="thead-light">
    <tr>
      <th>MobileNumber</th>
      <th>Amount</th>
      <th>Fuel</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1223445</td>
      <td>12.49</td>
      <td>1223</td>
    </tr>
    <tr>
      <td>99999</td>
      <td>11.39</td>
      <td>1277745</td>
    </tr>
  </tbody>
</table>

Couple of notes:

  • probably want name/value or Name/Value rather than Name/value
  • probably want TemplateFields



回答3:


here you are:

let tab = document.getElementById("tab");
let names = tab.querySelectorAll("th");
let values = tab.querySelector("tbody").children;

let arr = [];

for(let i =0; i < values.length;i++){
  let obj = {};
  for(let j = 0;j < names.length;j++){
    obj[names[j].innerHTML] = values[i].children[j].innerHTML;
  }
  arr.push(obj);
}

console.log(JSON.stringify(arr));

but it's not good solution



来源:https://stackoverflow.com/questions/58186602/convert-html-rows-into-name-value-pair-in-jquery

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!