jQuery 将 HTML 表格数据转换为 JSON 对象 [英] Convert a HTML table data into a JSON object in jQuery

查看:48
本文介绍了jQuery 将 HTML 表格数据转换为 JSON 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有谁知道如何将一个 HTML 值表转换为一个很好的 JSON 对象以使用 jQuery 进行操作?

Anyone know how to convert an HTML table of values into a nice JSON object to be manipulated with jQuery?

推荐答案

HTML 表格?比如,二维数组中的所有 内容?

An HTML table? Like, all the <td> contents in a 2-d array?

var tbl = $('table#whatever tr').map(function() {
  return $(this).find('td').map(function() {
    return $(this).html();
  }).get();
}).get();

然后只需使用 $.json(或您想要的任何库)将其转换为 JSON 字符串.

Then just use $.json (or whatever library you want) to turn that into a JSON string.

编辑 —重新编写以使用本机(此处填充) .map() 来自数组原型:

edit — re-written to use the native (shim here) .map() from the array prototype:

var tbl = $('table#whatever tr').get().map(function(row) {
  return $(row).find('td').get().map(function(cell) {
    return $(cell).html();
  });
});

jQuery .map() 函数具有将返回数组展平为结果数组的特性".也就是说,如果回调函数返回一个本身就是数组的值,那么返回的数组不是成为 .map() 结果的 one 单元格的值,它的每个元素都添加到结果中.

The jQuery .map() function has the "feature" of flattening returned arrays into the result array. That is, if the callback function returns a value that is itself an array, then instead of that returned array becoming the value of one cell of the .map() result, its elements are each added to the result.

可能使用原始的 jQuery 版本,只需在返回值周围包装一个额外的数组.

It might work to use the original jQuery version and just wrap an extra array around the returned values.

这篇关于jQuery 将 HTML 表格数据转换为 JSON 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆