原生JavaScript,根据后端返回JSON动态【动态列头、动态数据】生成表格数据

news2024/10/7 8:31:29

前期准备: JQ下载地址: https://jquery.com/

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>JSON动态生成表格数据,动态列头拼接</title>
		<style>
			table {
				width: 800px;
				text-align: center;
				border-collapse: collapse;
			}
			
			thead tr {
				height: 40px;
				background-color: rgb(161, 143, 143);
			}
			
			td,
			th {
				padding: 5px;
				border: 1px solid rgb(80, 73, 73);
			}
		</style>
	</head>
	<body>
		<div id="tableContainer"></div>
	</body>
	<!-- 下载地址: https://jquery.com/, 引入Jqurey,需要根据自己的JQ文件修改路径并引入 -->
	<script src="./jquery-3.7.1.min.js"></script>
	<script>
		function run() {
			var list = [{
					line: "line1",
					station: "stationA",
					device: "设备1",
					machine: "line1机台数据"
				}, {
					line: "line1",
					station: "stationB",
					device: "设备B",
					machine: "line1机台数据"
				},
				{
					line: "line1",
					station: "stationA",
					device: "设备2",
					machine: "机台数据"
				}, {
					line: "line1",
					station: "stationC",
					device: "设备C",
					machine: "line1机台数据"
				}, {
					line: "line2",
					station: "stationC",
					device: "设备C",
					machine: "line2机台数据"
				},
				{
					line: "line2",
					station: "stationA",
					device: "设备1",
					machine: "line2机台数据"
				},
				{
					line: "line2",
					station: "stationA",
					device: "设备2",
					machine: ""
				}, {
					line: "line3",
					station: "stationC",
					device: "设备C",
					machine: "line3机台数据"
				}
			]
			let column = [{
					label: '',
					key: 'station'
				},
				{
					label: '设备',
					key: 'device'
				}
			]
			let newLine = []
			let newStation = []
			for (var i = 0; i < list.length; i++) {
				let item = list[i]
				// 线别
				let lines = findArrIsNow(newLine, item.line)
				if (!lines) {
					newLine.push(item.line)
				}
				// station
				let stations = findArrIsNow(newStation, item.station)
				if (!stations) {
					newStation.push(item.station)
				}
			}
			// 组装头部
			for (var i = 0; i < newLine.length; i++) {
				let line = newLine[i]
				column.push({
					label: line,
					key: line
				})
			}
			// 组装数据
			let dataList = []
			for (var i = 0; i < newStation.length; i++) {
				let col = newStation[i]
				for (var j = 0; j < list.length; j++) {
					let lsItem = list[j]
					// 匹配对应的站点
					if (col === lsItem['station']) {
						// 查找设备名是否存在
						let deviceFinds = findObjectArrIsNow(dataList, 'device', lsItem['device'])

						// 不存在就添加
						if (!deviceFinds) {
							let obj = {
								station: col
							}
							obj['device'] = lsItem['device']
							obj[lsItem['line']] = lsItem['machine']
							dataList.push(obj)
						} else {
							deviceFinds[lsItem['line']] = lsItem['machine']
						}
					}
				}
			}
			document.getElementById('tableContainer').innerHTML = createTable(dataList, column, newLine);
			setTimeout(() => {
				mergeCell('myTable', [0])
			}, 500)
		}
		// 表格拼接
		function createTable(dataList, columnList, lineList) {
			var table = '<table id="myTable" border="1">';
			// 组装头部
			let headrs = '<tr>'
			for (var i = 0; i < columnList.length; i++) {
				let colTitles = columnList[i]
				headrs += '<th>' + colTitles.label + '</th>'
			}
			headrs += '</tr>';
			// 组装body
			let bodys = ''
			for (var i = 0; i < dataList.length; i++) {
				bodys += '<tr>';
				for (let tl of columnList) {
					// 第一列相同站点需要合并,特殊标记处理
					if (tl.key === 'station') {
						if (!dataList[i][tl.key]) {
							bodys += '<td rowspan=""></td>';
						} else {
							bodys += '<td rowspan="">' + dataList[i][tl.key] + '</td>';
						}
					} else {
						if (!dataList[i][tl.key]) {
							bodys += '<td></td>';
						} else {
							bodys += '<td>' + dataList[i][tl.key] + '</td>';
						}
					}
				}
				bodys += '</tr>';
			}
			table += headrs + bodys
			table += '</table>';
			return table;
		}

		// 查找数组对象是否存在 [{...}]
		function findObjectArrIsNow(list, key, value) {
			return list.find((fid) => {
				return fid[key] === value
			})
		}

		// 查找数组里是否存在 ['']
		function findArrIsNow(list, value) {
			return list.find((fid) => {
				return fid === value
			})
		}

		/**
		 * @param tableId  table的id
		 * @param cols     需要合并的列
		 */
		function mergeCell(tableId, cols) {
			var table = document.getElementById(tableId);
			var table_rows = table.rows;
			cols.forEach(v => { // 需要合并的列的数组
				for (let i = 0; i < table_rows.length - 1; i++) { // 循环table每一行
					// row
					let now_row = table_rows[i];
					let next_row = table_rows[i + 1];
					// col
					let now_col = now_row.cells[v];
					let next_col = next_row.cells[v];
					if (now_col.innerHTML == next_col.innerHTML) { // 判断内容是否相同
						$(next_col).addClass('remove'); // 标记为需要删除的列dom
						setParentSpan(table, i, v);
					}
				}
			})
			$(".remove").remove();
		}

		/**
		 * @param table  table的dom
		 * @param row    内容相同行
		 * @param col    内容相同列
		 */
		function setParentSpan(table, row, col) {
			var col_item = table.rows[row].cells[col];
			if ($(col_item).hasClass('remove')) {
				setParentSpan(table, --row, col)
			} else {
				col_item.rowSpan += 1;
			}
		}

		// 运行
		run()
	</script>
</html>

效果图:
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/27ffb12a0bce4c08a4457c754128fd29.png

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1501967.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

MySQL安装与卸载

安装 1). 双击官方下来的安装包文件 2). 根据安装提示进行安装(全部默认就可以) 安装MySQL的相关组件&#xff0c;这个过程可能需要耗时几分钟&#xff0c;耐心等待。 输入MySQL中root用户的密码,一定记得记住该密码 配置 安装好MySQL之后&#xff0c;还需要配置环境变量&am…

释机器学习中的召回率、精确率、准确率

精确率和召回率又被叫做查准率和查全率&#xff0c;可以通过P-R图进行表示 如何理解P-R(精确率-召回率)曲线呢&#xff1f;或者说这些曲线是根据什么变化呢&#xff1f; 以逻辑回归举例&#xff0c;其输出值是0-1之间的数字。因此&#xff0c;如果我们想要判断用户的好坏&…

Qt 自绘进度条 QProgressBar使用

文章目录 效果图控件介绍绘制函数总结 效果图 控件介绍 QProgressBar是Qt框架中提供的一个控件&#xff0c;用于在界面上显示任务的进度。它通常用于向用户展示一个操作完成的百分比&#xff0c;比如文件复制、数据加载等操作的进度。 QProgressBar的主要特性&#xff1a; 范…

linux应用程序需要编写的脚本

每一个程序都按照下面的要求进行脚本编写 多个应用之间联合安装采用编写外围脚本&#xff0c;依次调用多个应用的脚本的方式实现

【elasticsearch】ES的JAVA工具类完整版(待完成...)

springboot 的 elasticsearch 版本: 7.15.2 前情提要: 1.首先要理解 elasticsearch 对于【数据类型】很严格,如果字段类型不规范,在 检索/排序/聚合 时候类型不正确就会出现报错或者查不到数据的问题。所以在一般String类型插入结构如下: 这样的结构,不仅可以支持分词查…

css 背景图片居中显示

background 简写 background: #ffffff url(https://profile-avatar.csdnimg.cn/b9abdd57de464582860bf8ade52373b6_misnice.jpg) center center / 100% no-repeat;效果如图&#xff1a;

ubuntu 卸载miniconda3

一开始安装路径错了&#xff0c;需要重新安一次&#xff0c;就一起记录了。 前提是这种方式安装&#xff1a; ubuntu安装miniconda3管理python版本-CSDN博客 删除Miniconda的安装目录 这目录就是你选择安装的时候指定的&#xff0c;如果记不得了,可以这样查看 which conda 这…

docker拉取镜像失败的解决方案大全

更换国内源 创建或修改 /etc/docker/daemon.json 文件&#xff0c;修改&#xff1a; {"registry-mirrors" : ["https://registry.docker-cn.com","http://hub-mirror.c.163.com","https://docker.mirrors.ustc.edu.cn","https:…

【生态适配】亚信安慧AntDB数据库与OpenCloudOS、TencentOS Server五款产品完成兼容互认

日前&#xff0c;亚信安慧AntDB数据库与OpenCloudOS8、OpenCloudOS9、TencentOS Server 2、TencentOS Server 3、TencentOS Server 4五款操作系统完成兼容互认。经过严格测试&#xff0c;亚信安慧AntDB数据库与这五款操作系统兼容良好&#xff0c;整体运行稳定。 图1&#xff1…

全面认识计算机

目录 一、计算机的发展史 1. 电子管计算机时代 2. 晶体管计算机时代 3. 小、中规模集成电路计算机时代 4. 大、超大规模集成电路计算机时代 二、计算机硬件组成 1. 输入设备 2. 输出设备 3. 存储器 4. 运算器 5. 控制器 三、计算机硬件间的连接 四、计算机系统的结…

0201安装报错-hbase-大数据学习

1 基础环境简介 linux系统&#xff1a;centos&#xff0c;前置安装&#xff1a;jdk、hadoop、zookeeper&#xff0c;版本如下 软件版本描述centos7linux系统发行版jdk1.8java开发工具集hadoop2.10.0大数据生态基础组件zookeeper3.5.7分布式应用程序协调服务hbase2.4.11分布式…

Pytorch学习 day07(神经网络基本骨架的搭建、2D卷积操作、2D卷积层)

神经网络基本骨架的搭建 Module&#xff1a;给所有的神经网络提供一个基本的骨架&#xff0c;所有神经网络都需要继承Module&#xff0c;并定义_ _ init _ _方法、 forward() 方法在_ _ init _ _方法中定义&#xff0c;卷积层的具体变换&#xff0c;在forward() 方法中定义&am…

Java设计模式:适配器模式的三种形式(五)

码到三十五 &#xff1a; 个人主页 心中有诗画&#xff0c;指尖舞代码&#xff0c;目光览世界&#xff0c;步履越千山&#xff0c;人间尽值得 ! 适配器模式用于将一个类的接口转换为客户端所期望的另一个接口&#xff0c;以实现不兼容接口之间的协作。它像电器插头转换器一样…

单调栈(例题+解析)

1、应用场景 找出一个数的左面离概述最近的且小于该数的数&#xff08;同理右面也可以&#xff09; 例如&#xff1a; 数组a[i] 3 4 2 7 5 答案&#xff1a; -1 3 -1 2 2 2、如何实现找到规律 暴力写法&#xff1a; for(int i0;i<n;i) {for(int ji-1;j>0;j--){i…

金融数据采集与风险管理:Open-Spider工具的应用与实践

一、项目介绍 在当今快速发展的金融行业中&#xff0c;新的金融产品和服务层出不穷&#xff0c;为银行业务带来了巨大的机遇和挑战。为了帮助银行员工更好地应对这些挑战&#xff0c;我们曾成功实施了一个创新的项目&#xff0c;该项目采用了先进的爬虫技术&#xff0c;通过ope…

苍穹外卖学习-----2024/03/08

1.新增菜品 工具类AliOssUtil .java Data AllArgsConstructor Slf4j public class AliOssUtil {private String endpoint;private String accessKeyId;private String accessKeySecret;private String bucketName;/*** 文件上传** param bytes* param objectName* return*/pub…

STM32day3

1.思维导图 1.总结任务的调度算法&#xff0c;把实现代码再写一下 /* Definitions for myTask02 */ osThreadId_t myTask02Handle; uint32_t myTask02Buffer[ 64 ]; osStaticThreadDef_t myTask02ControlBlock; const osThreadAttr_t myTask02_attributes {.name "myTa…

PostgreSQL容器安装

docker中的centos7中安装 选择对应的版本然后在容器中的centos7中执行下面命令 但是启动容器的时候需要注意 开启端口映射开启特权模式启动init进程 docker run -itd --name centos-postgresql -p 5433:5432 --privilegedtrue centos:centos7 /usr/sbin/init 启动然后进入后先…

Mysql的Cardinality值

什么是Cardinality值&#xff1f; Cardinality值是Mysql做索引优化时一个非常关键的值&#xff0c;优化器会根据这个值来判断是否使用这个索引&#xff0c;它表示索引中唯一值的数目估计值&#xff0c;该值应该尽可能接近1&#xff0c;如果非常小&#xff0c;则用户需要考虑是否…

Clickhouse表引擎介绍

作者&#xff1a;俊达 1 引擎分类 ClickHouse表引擎一共分为四个系列&#xff0c;分别是Log、MergeTree、Integration、Special。其中包含了两种特殊的表引擎Replicated、Distributed&#xff0c;功能上与其他表引擎正交&#xff0c;根据场景组合使用。 2 Log系列 Log系列…