简体   繁体   English

我如何在运行时使用jquery创建json对象数组?

[英]How do i create array of json object at runtime using jquery?

I am trying to get array of json object from html table using jquery. 我正在尝试使用jquery从html表中获取json对象的数组。 This table and data will be determined during runtime and hold different data. 该表和数据将在运行时确定并保存不同的数据。 So I would like to get property for json object from thead td and values from tbody td. 所以我想从thead td获取json对象的属性,并从tbody td获取值。

 <table id="myTable"> <thead> <tr> <td>Name</td> <td>Gender</td> </tr> </thead> <tbody> <tr> <td>Mary Jane</td> <td>Female</td> </tr> <tr> <td>Peter Parker</td> <td>Male</td> </tr> </tbody> </table> 

I am able to create array of json object but I have to write property hard coded. 我能够创建json对象的数组,但我必须编写硬编码的属性。 var jsonList = [{"Name":"Mary Jane", "Gender":"Female"},{"Name":"Peter Parker", "Gender":"Male"}]

My code: 我的代码:

 var data = []; var target = $('#myTable tr').not('thead tr'); target.each(function (i) { console.log($(this).find('td:eq(0)').html()); data.push({ "Name": $(this).find('td:eq(0)').html(), "Gender": $(this).find('td:eq(1)').html() }); }); var json =JSON.stringify(data); 

How do i do this using jquery ? 我如何使用jquery做到这一点?

You could first get cells from thead in an array and then loop each row in tbody and use cell index to get the property name from the thead with the same index. 您可以首先从thead中获取数组中的单元格,然后在tbody循环每一行,并使用cell index从具有相同索引的thead中获取属性名称。

 let th = $("#myTable thead tr td").map(function() { return $(this).text() }).get(); let data = $("#myTable tbody tr").map(function() { return Array.from($(this).find("td")).reduce(function(r, td, i) { r[th[i]] = td.textContent; return r; }, {}) }).get() console.log(data) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table id="myTable"> <thead> <tr> <td>Name</td> <td>Gender</td> </tr> </thead> <tbody> <tr> <td>Mary Jane</td> <td>Female</td> </tr> <tr> <td>Peter Parker</td> <td>Male</td> </tr> </tbody> </table> 

 var headers = $('#myTable thead tr:eq(0)').find('td, th').map(function () { return $(this).text(); }).get(); var data = $('#myTable tbody tr').map(function () { return Array.from($(this).find('td')).reduce(function (accumulator, current, index) { accumulator[headers[index]] = $(current).text(); return accumulator; }, {}); }).get(); var json = JSON.stringify(data); console.log(json); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table id="myTable"> <thead> <tr> <td>Name</td> <td>Gender</td> </tr> </thead> <tbody> <tr> <td>Mary Jane</td> <td>Female</td> </tr> <tr> <td>Peter Parker</td> <td>Male</td> </tr> </tbody> </table> 

there you go 你去

var a = $(`<table id="myTable">
  <thead>
    <tr>
      <td>Name</td>
      <td>Gender</td>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Mary Jane</td>
      <td>Female</td>
    </tr>
    <tr>
      <td>Peter Parker</td>
      <td>Male</td>
    </tr>
  </tbody>
</table>`);

var keys = a
  .find("thead tr td")
  .toArray()
  .map(x => x.textContent);

var result = a
  .find("tbody tr")
  .map((i, tr) => {
    var obj = {};
    $(tr)
      .find("td")
      .each((i, td) => (obj[keys[i]] = td.innerText));
    return obj;
  })
  .toArray();

console.log(result);

There are a few things you can do to make this a bit easier if you are able to edit the HTML: 如果您能够编辑HTML,可以采取一些措施使此操作变得容易一些:

First I would change the td in the thead to th . 首先,我将thead中td更改为th This will help out the JavaScript, and is also better semantically. 这将有助于JavaScript,并且在语义上也更好。

 var data = []; var $myTable = $('#myTable'); //keeping the table in memory is a bit more effcient var labels = $myTable.find('thead th').toArray().map(function(th) { //toArray converts the jQuery object to a standard JavaScript array so that we can use the native .map method. return th.innerHTML.trim(); //innerHTML is like jQuery .text(), .trim() removes any whitespace on the left or right. }); //["Name","Gender"] var $rows = $myTable.find('tbody tr'); $rows.each(function() { var $row = $(this); var row_data = {}; for (let i = 0; i < labels.length; i++) { //native JS for loop row_data[labels[i]] = $row.find('td:eq(' + i + ')').text().trim(); } data.push(row_data); }); console.log(data); var json_data = JSON.stringify(data); //array of objects in string format 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table id="myTable"> <thead> <tr> <th>Name</th> <th>Gender</th> </tr> </thead> <tbody> <tr> <td>Mary Jane</td> <td>Female</td> </tr> <tr> <td>Peter Parker</td> <td>Male</td> </tr> </tbody> </table> 

So what's going on with the JavaScript? 那么JavaScript到底是怎么回事? First I'm keeping the table in memory as $myTable and finding the elements we need inside of it from there. 首先,我将表作为$ myTable保留在内存中,并从那里查找我们需要的元素。 To find the labels, I've used jQuery .toArray() to convery the jQuery object to a vanilla JavaScript array so that we can use .map() . 为了找到标签,我使用jQuery .toArray()将jQuery对象转换为普通JavaScript数组,以便我们可以使用.map() Map is a very useful method as whatever you return to from the callback gets pushed onto the new array that I've called labels. Map是一个非常有用的方法,因为您从回调返回的任何内容都会被推送到我称为标签的新数组上。

Next we gets all the rows from $myTable and loop over them like you were doing. 接下来,我们从$ myTable获取所有行,并像您一样在它们上循环。 Instead of hard coding the object keys, I'm looping over the labels array we made earlier. 我没有对对象键进行硬编码,而是遍历了我们之前制作的标签数组。 I'm also using the temporary variable i to find the td that you wanted. 我还使用临时变量i查找所需的td。 Finally push the constructed object to the end of the array. 最后,将构造的对象推到数组的末尾。

Please note!! 请注意!! That is there is any broken HTML on the page, or a row has some missing data, you will have issues with your data as well. 那就是页面上有任何损坏的HTML,或者一行中有一些丢失的数据,您的数据也会有问题。 If you are able to edit HTML, but need the data from in JavaScript, I suggest using an application/json tag like so: 如果您能够编辑HTML,但需要JavaScript中的数据,则建议使用application / json标记,如下所示:

 var $myData = $('#myData'); var json_data = $myData.text(); //if you just need string data, stop here! console.log(json_data); var data = JSON.parse(json_data); console.log(data); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script id="myData" type="application/json"> [{ "Name": "Mary Jane", "Gender": "Female" }, { "Name": "Peter Parker", "Gender": "Male" }] </script> 

I hope this helps :) 我希望这有帮助 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM