ts implements merging data with the same key in array objects

background

In normal business, the back-end students will return structural data similar to the following

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

Front-end display needs to be classified and displayed, so data like [{parent: "xx", child: [{xx},{xx}]}] needs to be constructed

// 前端处理后的结构
[
    { 
        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" }
        ]
    } 
]

Merge data with the same key in array objects

Construct [ { parent: "xx", child: [ { xx }, { xx } ] } ], you need to pass in the data source and match the merged key

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" });
};

final presentation

~~ END ~~

Guess you like

Origin blog.csdn.net/weixin_45313351/article/details/134545419