一个对象数组中根据相同id合并,对象转数组

2024年07月30日 建站教程

基础数据

let eduLevelArray = [
{
	id: "1",
	name: "张三",
	edu: "小学"
},{
	id: "2",
	name: "李四",
	edu: "初中"
},{
	id: "1",
	name: "张三",
	edu: "高中"
},{
	id: "2",
	name: "李四",
	edu: "大学"
},{
	id: "3",
	name: "王五",
	edu: "研究生"
}];

执行方法

let reArr = eduLevelArray.reduce((obj, item) => {
	if(obj[item.id]){
	   obj[item.id].edu.push(item.edu)
	}else{
	   item.edu = [item.edu]   
	   obj[item.id] = {...item}
	}
	 return obj;
}, {});

//执行Object方法
let mergedArray = Object.values(reArr);

console.log(mergedArray)

输出结果:

mergedArray = [{
	id: "1",
	name: "张三",
	edu:["小学", "高中"]
},{
	id: "2",
	name: "李四",
	edu: ["初中", "大学"]
},{
	id: "3",
	name: "王五",
	edu: ["研究生"]
}]

本文链接:http://so.lmcjl.com/news/9502/

展开阅读全文
相关内容