按嵌套属性ID合并对象数组 实现同ID关联的尺寸数据合并为单个数组
实现按嵌套ID合并对象数组的方案
核心思路是先对productSizes做分组聚合,代替直接使用map遍历生成新对象:
- 用
Map结构存储已出现的分组ID对应的条目,键为分组ID,值为聚合后的分组对象 - 遍历所有尺寸数据时,遇到已存在的分组ID就将当前尺寸推入对应条目的
items数组,不存在则初始化新分组 - 最后将Map的value转为数组,作为外层的
items属性值
完整实现代码
const groupMap = new Map(); // 遍历所有尺寸数据完成分组 productSizes.forEach(productSize => { const currentGroupId = productSize.groupId; const currentLabel = currentGroupId.split('-')[0]; const currentSize = productSize.size; if (groupMap.has(currentGroupId)) { // 同ID分组已存在,追加尺寸数据到items数组 groupMap.get(currentGroupId).items.push(currentSize); } else { // 同ID分组不存在,初始化分组,items默认设为数组格式 groupMap.set(currentGroupId, { id: currentGroupId, label: currentLabel, items: [currentSize] }); } }); // 生成最终结果 const finalResult = { id: 'productId', label: 'productLabel', items: Array.from(groupMap.values()) };
说明
- 该方案仅需遍历一次
productSizes数组,时间复杂度为O(n),执行效率更高 - 输出结构完全匹配需求格式,相同ID对应的所有尺寸都会被整合到同一个
items数组中
内容的提问来源于stack exchange,提问作者Nightcorey
相关产品推荐
相关产品推荐

