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

背景

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

// 后端返回的数据结构
[
    { 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}]}] 这样的数据

// 前端处理后的结构
[
    { 
        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 } ] } ] ,需要传入数据源,匹配合并的键

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);
};
const showRegionList = (regionArr: ICoupon.AvailabilityZone[]) => {
	return mergeByKey<ICoupon.AvailabilityZone>({ dataSource: regionArr, key: "pid", prop: "pid_name" });
};

最终的展示

~~ END ~~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值