后端返回的一维数组的数据,但是前端展示需要3个一排展示
// 后端返回的数据:
const data = [
{checkedName: '检查项1', status: '合格'},
{checkedName: '检查项2', status: '合格'},
{checkedName: '检查项3', status: '不合格'},
{checkedName: '检查项4', status: '合格'},
{checkedName: '检查项5', status: '合格'},
{checkedName: '检查项6', status: '不合格'},
]
页面实际要展示的效果:这时候需要将一维数组的数据拆分成二维数组,然后用两次循环去渲染dom会更方便一点
具体方法:
const data = [
{checkedName: '检查项1', status: '合格'},
{checkedName: '检查项2', status: '合格'},
{checkedName: '检查项3', status: '不合格'},
{checkedName: '检查项4', status: '合格'},
{checkedName: '检查项5', status: '合格'},
{checkedName: '检查项6', status: '不合格'}
]
const newData= data.reduce((prev, curr, index) => {
// 下面的3就是一行要显示的数量
const i = Math.floor(index/3)
prev[i] = [...prev[i]||[], curr]
return prev
}, [])
// 打印一下newData
[
[{checkedName: '检查项1', status: '合格'}, {checkedName: '检查项2', status: '合格'}, {checkedName: '检查项3', status: '不合格'}],
[{checkedName: '检查项4', status: '合格'}, {checkedName: '检查项5', status: '合格'}, {checkedName: '检查项6', status: '不合格'}],
]