Vue实战(十):对数组数据的拆分和分组合并

Vue实战(十):对数组数据的拆分和分组合并

数据初始化

js 复制代码
//第一种情况
tableData: [
	{ id: 1, name: ["A", "B"] },
	{ id: 2, name: ["A", "C"] },
	{ id: 3, name: ["B", "C"] },
	{ id: 4, name: ["A", "B", "C"] },
],
//第二种情况
tableData1: [
	{ id: 1, name: ["A"] },
	{ id: 2, name: ["B"] },
	{ id: 3, name: ["C"] },
],
//第三种情况
tableData2: [
	{ id: 1, name: ["A"] },
	{ id: 2, name: ["A"] },
	{ id: 3, name: ["C"] },
],

分解数据

js 复制代码
separateData(arr) {
	let newArr = [];
	arr.forEach((item) => {
		item.name.forEach((it) => {
			var obj = {};
			this.$set(obj, "id", item.id);
			this.$set(obj, "name", it.split(","));
			newArr.splice(newArr.length, 0, obj);
		});
	});
	return newArr;
}

分组数据

js 复制代码
groupBy(objectArray, property) {
	return objectArray.reduce(function (acc, obj) {
		var key = obj[property];
		if (!acc[key]) {
			acc[key] = [];
		}
		acc[key].push(obj);
		return acc;
	}, {});
}

第一种情况测试

js 复制代码
console.log(JSON.stringify(this.tableData));
let arr = this.separateData(this.tableData);
console.log(JSON.stringify(arr));
let result = this.groupBy(arr, "name");
console.log(JSON.stringify(result));

第二种情况测试

js 复制代码
console.log(JSON.stringify(this.tableData1));
let arr = this.separateData(this.tableData1);
console.log(JSON.stringify(arr));
let result = this.groupBy(arr, "name");
console.log(JSON.stringify(result));

第三种情况测试

js 复制代码
console.log(JSON.stringify(this.tableData2));
let arr = this.separateData(this.tableData2);
console.log(JSON.stringify(arr));
let result = this.groupBy(arr, "name");
console.log(JSON.stringify(result));
相关推荐
如烟花的信页13 分钟前
易盾点选逆向分析
javascript·爬虫·python·js逆向
ZC跨境爬虫19 分钟前
跟着 MDN 学 JavaScript day_2:JavaScript 初体验
开发语言·前端·javascript·学习·ecmascript
假如让我当三天老蒯34 分钟前
useCallback 详细解释(从原理到用法)(自学用)
前端·react.js
小妖66639 分钟前
Hydration completed but contains mismatches
javascript·vue·vuepress
a1117761 小时前
粒子化系统(3D-Particles)THreeJS react
前端·html·jetson
码农君莫笑1 小时前
深入理解 CSS Grid 布局:从入门到实战
前端·css
睡觉的时候不困61 小时前
TypedSql:在 C# 类型系统上实现一个 SQL 查询引擎
javascript
AI英德西牛仔1 小时前
Claude 导出 pdf 颜色不一样怎么办,选用 AI 导出鸭优化格式转换,多维度落地修正 PDF 色彩失真问题
javascript·人工智能·ai·chatgpt·pdf·deepseek·ai导出鸭
yingyima1 小时前
Azure Functions 定时触发器配置:Cron vs. TimerTrigger,谁主沉浮?
前端