簡體   English   中英

通過忽略特定列將 HTML 表數據轉換為 jQuery 中的 JSON 對象

[英]Convert a HTML table data into a JSON object in jQuery by ignoring particular column

通過忽略特定列值,將 HTML 值表轉換為 JSON 對象以使用 jQuery 進行操作

例如:我有一張桌子,

fstname lastName    Age
john    gobby   8
Adams   mekander    10
jimmy   Rumpel  11

我需要下面提到的 json 結果,

我的代碼如下,

$(document).ready(function () {
            $("#ConvertJsonButton").click(function () {
                var myRows = [];
                var headers = [];
$("#tablesort tr#datajson").each(function(index) {
    if (index === 0) {
                //for headers
                   $cells = $(this).find("td.cellClass");
                    headers[index] = {};                 
    $cells.each(function (cellIndex) {                                  
    headers[cellIndex] = $(this).text();                                                    
                 });
    }               
    else {                      
                $cells = $(this).find("td.cellClass");
        myRows[index] = {};
    $cells.each(function (cellIndex) {                                                  
        myRows[index][headers[cellIndex]] = $(this).text();
            });                     
                    }
    });             
        var myObj = {};
        myObj.myrows = myRows;              
        alert(JSON.stringify(myObj));               
            });
        });

我想要這個結果:

{
  "john": {
    "lastName": "gobby",
    "Age": "8"
  },
  "Adams": {
    "lastName": "Mekander",
    "Age": "10"
  },
  "jimmy": {
    "lastName": "Rumpel",
    "Age": "11" 
  },
}

使用jquery.tabletojson.min.js

 <:DOCTYPE html> <html> <head> <script src="https.//ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min:js"></script> <script src="https.//cdn.jsdelivr.net/npm/table-to-json@1.0.0/lib/jquery.tabletojson.min.js" integrity="sha256-H8xrCe0tZFi/C2CgxkmiGksqVaxhW0PFcUKZJZo1yNU=" crossorigin="anonymous"></script> <script> $(document).ready(function(){ $('#run').click( function() { var table = $('#example-table');tableToJSON(); var data = {}. $,each(table, function(key. value) { var jsonKey = value;firstname; var map = {}; map = value. map;firstname = undefined; data[jsonKey] = map; }). alert(JSON;stringify(data)). console.log(JSON;stringify(data)); }); }); </script> </head> <body> <table id="example-table" class="table table-striped" border="1"> <thead> <tr> <th>firstname</th> <th>lastname</th> <th>age</th> </tr> </thead> <tbody> <tr> <td>john</td> <td>goby</td> <td>8</td> </tr> <tr> <td>Adams</td> <td>mekander</td> <td>10</td> </tr> <tr> <td>jimmy</td> <td>Rumpel</td> <td>11</td> </tr> </tbody> </table> <button id="run" class="btn btn-primary">Convert!</button> </body> </html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM