背景
在平常的業務中,后端同學會返回以下類似的結構數據
// 后端返回的數據結構
[{ 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" });
};
最終的展示