当前位置: 首页 > news >正文

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

http://www.lryc.cn/news/247888.html

相关文章:

  • C语言--根据成绩判断等级
  • Rust多线程任务,发现有些线程一直获取不到锁【已解决】
  • 【区块链】产品经理的NFT初探
  • 香港服务器减少延迟的几种方法
  • PowerShell命令小记
  • C语言小练
  • Webhook端口中的自签名身份验证
  • CSS预处理器(如Sass或Less):变量、嵌套规则和混合器等高级功能
  • 【Linux】Linux第一个小程序 --- 进度条
  • 每日一练:约瑟夫生者死者小游戏
  • 双指针算法(题目与答案讲解)
  • python服装电商系统vue购物商城django-pycharm毕业设计项目推荐
  • 数据治理技术:研究现状与数据规范
  • 一文彻底理解索引下推
  • Springboot3+vue3从0到1开发实战项目(一)
  • [字符串操作] 有年代的病历单
  • 怎么批量提取文件名字到Excel中?
  • QT搭建的Ros/librviz的GUI软件
  • Docker 概述与安装
  • JS作用域与作用域链
  • elmentui 查看大图组件 点击图片关闭弹窗方法
  • 蓝桥杯官网练习题(最长子序列)
  • Make sure that using this pseudorandom number generator is safe here.
  • 【C/C++】常见模拟题题解
  • TikTok 购物和直播的 5 个简单技巧
  • 神经网络中BN层简介及位置分析
  • BGP基础配置
  • 【开题报告】基于深度学习的驾驶员危险行为检测系统
  • Linux云服务器打包部署前端Vue项目
  • Egg.js中Cookie和Session