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));
相关推荐
niucloud-admin1 小时前
web 端前端
前端
摘星编程4 小时前
React Native for OpenHarmony 实战:Linking 链接处理详解
javascript·react native·react.js
胖者是谁4 小时前
EasyPlayerPro的使用方法
前端·javascript·css
EndingCoder4 小时前
索引类型和 keyof 操作符
linux·运维·前端·javascript·ubuntu·typescript
liux35284 小时前
Web集群管理实战指南:从架构到运维
运维·前端·架构
沛沛老爹4 小时前
Web转AI架构篇 Agent Skills vs MCP:工具箱与标准接口的本质区别
java·开发语言·前端·人工智能·架构·企业开发
摘星编程5 小时前
React Native for OpenHarmony 实战:ImageBackground 背景图片详解
javascript·react native·react.js
小光学长5 小时前
基于Web的长江游轮公共服务系统j225o57w(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
前端·数据库
摘星编程6 小时前
React Native for OpenHarmony 实战:Alert 警告提示详解
javascript·react native·react.js
Joe5566 小时前
vue2 + antDesign 下拉框限制只能选择2个
服务器·前端·javascript