首页 > 解决方案 > 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 个对象中的每一个。

在此处输入图像描述

标签: javascriptjqueryhtml

解决方案


您可以使用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>


推荐阅读