JS如何取出数组对象中具有相同属性值的元素,并归类放入另一个新对象中

Posted by YorkWong on May 10, 2022

原数据结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
detailList: [
	 {
		id: 147,
		parentId: 3,
		createDate: "2020-12-16 13:16:33",
		name: "33方法"
		},
	 {
		id: 148,
		parentId: 3,
		createDate: "2020-12-16 13:16:33",
		name: "嗯嗯发"
		},
]

目标数据结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
afterData: [
	{
		time: "2020-12-16",
		list: [
			{
				id: 147,
				parentId: 3,
				createDate: "2020-12-16 13:16:33",
				name: "33方法"
			},
			{
				id: 148,
				parentId: 3,
				createDate: "2020-12-16 13:16:33",
				name: "嗯嗯发"
			},
		]
}
]

实现办法

格式化时间字符串,在detailList中的每个元素插入一条格式化了的,形如 time:YY-MM-DD 的键值对数据

1
2
3
4
5
6
7
this.detailList.forEach(c => {
		c.time = this.$tools.dateFormat(
				'YYYY-mm-dd',
				new Date(c.createDate) //要把字符串转换为date对象,才能使用tools里面的方法
			);
		
			});	
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 年月日,时分秒 ==> "YYYY-mm-dd HH:MM"
dateFormat(fmt, date) {
	let ret;
	const opt = {
		"Y+": date.getFullYear().toString(), // 年
		"m+": (date.getMonth() + 1).toString(), // 月
		"d+": date.getDate().toString(), // 日
		"H+": date.getHours().toString(), // 时
		"M+": date.getMinutes().toString(), // 分
		"S+": date.getSeconds().toString() // 秒
		// 有其他格式化字符需求可以继续添加,必须转化成字符串
	};
	for (let k in opt) {
		ret = new RegExp("(" + k + ")").exec(fmt);
		if (ret) {
		fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
		};
	};
		return fmt;
	},

关键方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
let tempArr = [];
    for (let i = 0; i < this.detailList.length; i++) {
				// indexOf()方法返回在数组中可以找到一个给定元素的第一个索引,如果不存在,则返回-1。
				if (tempArr.indexOf(this.detailList[i].time) === -1) {
					this.afterData.push({
						time: this.detailList[i].time,
						list: [this.detailList[i]]
					});
					tempArr.push(this.detailList[i].time);
				} else {
					for (let j = 0; j < this.afterData.length; j++) {
						if (this.afterData[j].time == this.detailList[i].time) {
							this.afterData[j].list.push(this.detailList[i]);
							break;
						}
					}
				}
			}