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));
相关推荐
Csvn20 分钟前
页面「穿越」之谜:React 中因 key 值不正确导致的渲染 Bug 排查实战
前端
浅水壁虎21 分钟前
前端技术_TypeScript(第一章)
前端
你怎么知道我是队长35 分钟前
JavaScript 函数 this 全解
开发语言·javascript·ecmascript
laboratory agent开发1 小时前
企业AI Agent落地前,先回答四个工程问题
java·前端·人工智能
微三云 - 廖会灵 (私域系统开发)1 小时前
电商系统国际化架构设计:多语言、多币种、多时区、多税制的全链路实现
java·前端·数据库
不简说2 小时前
JS 代码技巧 vol.5 — 10 个错误处理套路,从 try/catch 到 Error Boundary
前端·javascript·程序员
wordpress资料库2 小时前
Next.js更适合移动开发 不适合web开发
开发语言·前端·javascript·next.js
卷无止境2 小时前
Quarkdown:赋予 Markdown 超能力的现代排版系统
前端·markdown
BerryS3N3 小时前
C++23新特性在CLion中的实战体验:从语法糖到生产力提升
前端·c++23
李明卫杭州3 小时前
Vue 3 `markRaw` 详解:什么时候该让一个对象"别被代理"
vue.js