如何用JavaScript将HTML表格数据转换为排除序号、编辑列的JSON数组
实现代码
原生JavaScript实现逻辑如下:
// 读取目标表格 const table = document.getElementById('stockinboundedittable'); const resList = []; // 跳过表头行,遍历所有数据行 for (let i = 1; i < table.rows.length; i++) { const currentRow = table.rows[i]; // 按列索引读取对应input的value值,组装指定字段的对象 const rowData = { itemname: currentRow.cells[2].querySelector('input').value.trim(), oldstock: currentRow.cells[3].querySelector('input').value.trim(), newstock: currentRow.cells[4].querySelector('input').value.trim(), totalstock: currentRow.cells[5].querySelector('input').value.trim() }; resList.push(rowData); } // 输出格式化后的JSON console.log(JSON.stringify(resList, null, 2));
对应你提供表格的转换结果
[ { "itemname": "Fresh Goat Meat - Curry Cut", "oldstock": "20", "newstock": "10", "totalstock": "30" }, { "itemname": "Everest - Kasur Methi", "oldstock": "0", "newstock": "10", "totalstock": "10" }, { "itemname": "Fresh Coconut Milk 150 ml", "oldstock": "10", "newstock": "10", "totalstock": "20" }, { "itemname": "Sakthi - Chicken Masala", "oldstock": "20", "newstock": "10", "totalstock": "30" }, { "itemname": "Goat Bones - Regular Soup Pack", "oldstock": "0", "newstock": "10", "totalstock": "10" } ]
内容的提问来源于stack exchange,提问作者A. Chithrai
相关产品推荐
相关产品推荐

