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 ~~

相关推荐
晴空万里藏片云36 分钟前
elment Table多级表头固定列后,合计行错位显示问题解决
前端·javascript·vue.js
曦月合一37 分钟前
html中iframe标签 隐藏滚动条
前端·html·iframe
奶球不是球39 分钟前
el-button按钮的loading状态设置
前端·javascript
kidding72343 分钟前
前端VUE3的面试题
前端·typescript·compositionapi·fragment·teleport·suspense
无责任此方_修行中2 小时前
每周见闻分享:杂谈AI取代程序员
javascript·资讯
Σίσυφος19003 小时前
halcon 条形码、二维码识别、opencv识别
前端·数据库
学代码的小前端3 小时前
0基础学前端-----CSS DAY13
前端·css
dorabighead4 小时前
JavaScript 高级程序设计 读书笔记(第三章)
开发语言·javascript·ecmascript
css趣多多4 小时前
案例自定义tabBar
前端
姑苏洛言5 小时前
DeepSeek写微信转盘小程序需求文档,这不比产品经理强?
前端