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

相关推荐
勿语&19 分钟前
Element-UI Plus 暗黑主题切换及自定义主题色
开发语言·javascript·ui
黄尚圈圈21 分钟前
Vue 中引入 ECharts 的详细步骤与示例
前端·vue.js·echarts
浮华似水1 小时前
简洁之道 - React Hook Form
前端
正小安3 小时前
如何在微信小程序中实现分包加载和预下载
前端·微信小程序·小程序
_.Switch5 小时前
Python Web 应用中的 API 网关集成与优化
开发语言·前端·后端·python·架构·log4j
一路向前的月光5 小时前
Vue2中的监听和计算属性的区别
前端·javascript·vue.js
长路 ㅤ   5 小时前
vite学习教程06、vite.config.js配置
前端·vite配置·端口设置·本地开发
长路 ㅤ   5 小时前
vue-live2d看板娘集成方案设计使用教程
前端·javascript·vue.js·live2d
Fan_web5 小时前
jQuery——事件委托
开发语言·前端·javascript·css·jquery
安冬的码畜日常5 小时前
【CSS in Depth 2 精译_044】第七章 响应式设计概述
前端·css·css3·html5·响应式设计·响应式