ts实现合并数组对象中key相同的数据

背景

在平常的业务中,后端同学会返回以下类似的结构数据

javascript 复制代码
// 后端返回的数据结构
[
    { id: 1, product_id: 1, pid_name: "Asia", name: "HKG01" },
    { id: 2, product_id: 1, pid_name: "Asia", name: "SH01" },
    { id: 3, product_id: 2, pid_name: "Europe", name: "NY04" },
    { id: 4, product_id: 2, pid_name: "Europe", name: "HK02" },
    { id: 5, product_id: 2, pid_name: "Europe", name: "HK10" },
    { id: 6, product_id: 1, pid_name: "Asia", name: "HKG05" }
]

前端展示时需要归类展示 ,因此需要构造 类似[{parent: "xx", child: [{xx},{xx}]}] 这样的数据

javascript 复制代码
// 前端处理后的结构
[
    { 
        parent: "Asia",
        child: [
            { id: 1, product_id: 1, pid_name: "Asia", name: "HKG01" },
            { id: 2, product_id: 1, pid_name: "Asia", name: "SH01" },
            { id: 5, product_id: 1, pid_name: "Asia", name: "HKG05" }
        ]
    } ,
    { 
        parent: "Europe", 
        child: [
            { id: 3, product_id: 2, pid_name: "Europe", name: "NY04" },
            { id: 4, product_id: 2, pid_name: "Europe", name: "HK02" },
            { id: 4, product_id: 2, pid_name: "Europe", name: "HK10" }
        ]
    } 
]

合并数组对象中key相同的数据

构造 [ { parent: "xx", child: [ { xx }, { xx } ] } ] ,需要传入数据源,匹配合并的键

javascript 复制代码
type MergeByKeyParam<T> = {
	dataSource: Array<T>; // 数据源
	key: string; // 匹配的键
	prop: string; // 匹配的键名
};
type MergeByKeyResult<T> = {
	parent: string;
	child: Array<T>;
};
export const mergeByKey = <T>({ dataSource, key, prop }: MergeByKeyParam<T>): Array<MergeByKeyResult<T>> => {
	const dataObj = {};
	for (const item of dataSource) {
		if (!dataObj[item[key]]) {
			dataObj[item[key]] = {
				parent: item[prop],
				child: []
			};
		}
		dataObj[item[key]].child.push(item);
	}
	return Object.values(dataObj);
};
javascript 复制代码
const showRegionList = (regionArr: ICoupon.AvailabilityZone[]) => {
	return mergeByKey<ICoupon.AvailabilityZone>({ dataSource: regionArr, key: "pid", prop: "pid_name" });
};

最终的展示

~~ END ~~

相关推荐
子兮曰13 小时前
OpenClaw入门:从零开始搭建你的私有化AI助手
前端·架构·github
吴仰晖13 小时前
使用github copliot chat的源码学习之Chromium Compositor
前端
1024小神13 小时前
github发布pages的几种状态记录
前端
不像程序员的程序媛15 小时前
Nginx日志切分
服务器·前端·nginx
Daniel李华15 小时前
echarts使用案例
android·javascript·echarts
北原_春希15 小时前
如何在Vue3项目中引入并使用Echarts图表
前端·javascript·echarts
JY-HPS15 小时前
echarts天气折线图
javascript·vue.js·echarts
尽意啊15 小时前
echarts树图动态添加子节点
前端·javascript·echarts
吃面必吃蒜15 小时前
echarts 极坐标柱状图 如何定义柱子颜色
前端·javascript·echarts
O_oStayPositive15 小时前
Vue3使用ECharts
前端·javascript·echarts