javascript - JSON 到 Html 表,每 2 个对象合并行
问题描述
假设,我有一个对象数组:
var jsonData = [{
"Mass": "3",
"Force": "3.1",
"Acceleration": "3"
}, {
"Mass": "3",
"Force": "4.1",
"Acceleration": "3"
}, {
"Mass": "4",
"Force": "4.1",
"Acceleration": "4"
}, {
"Mass": "4",
"Force": "4.1",
"Acceleration": "4"
}, {
"Mass": "0",
"Force": "0",
"Acceleration": "0"
}, {
"Mass": "0",
"Force": "0",
"Acceleration": "0"
}];
我想要的是将此 JSON 转换为这样的表,用于连续合并质量和加速度单元格的 2 个对象中的每一个。
解决方案
您可以使用reduce
方法和%
运算符将元素添加到每个第二个元素的数组中,然后基于该新数组构建表格。
var jsonData = [{"Mass":"3","Force":"3.1","Acceleration":"3"},{"Mass":"3","Force":"4.1","Acceleration":"3"},{"Mass":"4","Force":"4.1","Acceleration":"4"},{"Mass":"4","Force":"4.1","Acceleration":"4"},{"Mass":"0","Force":"0","Acceleration":"0"},{"Mass":"0","Force":"0","Acceleration":"0"}]
const result = jsonData.reduce((r, e, i, a) => {
// when index is 0, 2, 4 ... (every 2nd)
if (i % 2 == 0) {
// get also the next element 1, 3, 5
const next = a[i + 1];
// create a copy of current element and force as array
const obj = { ...e, Force: [e.Force] }
// if there is next element push its force to array
if (next) obj.Force.push(next.Force);
// push that new object to accumulator
r.push(obj)
}
return r;
}, []);
const table = $('table');
const thead = table.find('thead');
const tbody = table.find('tbody');
Object.keys(result[0]).forEach(key => {
thead.append($('<th>', {
text: key
}))
})
result.forEach(e => {
const row = $('<tr>');
row.append($('<td>', {
text: e.Mass
}));
const force = $('<td>');
e.Force.forEach(f => {
const forceRow = $("<tr>");
forceRow.append($('<td>', {
text: f
}));
force.append(forceRow);
});
row.append(force);
row.append($('<td>', {
text: e.Acceleration
}));
tbody.append(row)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="1">
<thead></thead>
<tbody></tbody>
</table>
推荐阅读
- pyinstaller - 在EXE中使用PyInstaller打包数据文件
- c++ - 通过 lambda 部分专门化类模板
- c# - 如何正确反序列化 Json DateTimeOffset?
- ruby - 如何将字符串拆分为 n 个子字符串?
- php - 显示错误:上传路径似乎无效
- c# - 有没有办法禁用所有 WPF 应用程序的缩放,即使 Windows 在每个监视器或系统范围内都有一定的缩放比例?
- cuda - Cuda - nvcc - 没有可在设备上执行的内核映像。问题是什么?
- html - 在 Chrome 中编辑 CSS 规则时不要突出显示 HTML 区域
- mysql - 如何在执行 SQL 转储时替换某些列的值
- css - 如何在不重置 CSS 的情况下添加 Bootstrap?