You need to enable JavaScript to run this app. 使用ES6重排含相同ID项的数组:产品按所属店铺聚合
优惠活动
大模型
产品
解决方案
定价
更多

使用ES6重排含相同ID项的数组:产品按所属店铺聚合

按店铺归集产品的实现

最简洁高效的方式是通过reduce做分组归集,以店铺的唯一id作为匹配key,避免重复遍历查找。

可直接运行的示例代码

const products = [
 { title: 'test product', storefront: {id: 0, title: 'test storefront 1'} },
 { title: 'test product 2', storefront: {id: 0, title: 'test storefront 1'} },
 { title: 'test product 3', storefront: {id: 1, title: 'test storefront 2'} }
]

// 用临时对象按店铺id归集数据,减少重复查找开销
const groupedByStore = products.reduce((group, product) => {
  const storeId = product.storefront.id
  // 首次遇到该店铺时初始化对应结构
  if (!group[storeId]) {
    group[storeId] = {
      storefront: product.storefront,
      products: []
    }
  }
  group[storeId].products.push(product)
  return group
}, {})

// 将中间归集的对象转为要求的数组格式
const storefronts = Object.values(groupedByStore)

实现说明

  • 相比每次遍历结果数组匹配店铺id的方式,用对象做key-value存储的分组方式时间复杂度为O(n),处理大量产品时性能优势明显
  • 直接复用产品里自带的店铺信息对象作为输出里的storefront字段,不需要额外拷贝结构,和示例输出完全一致
  • 逻辑本身兼容空数组输入,当products为空时,最终输出也是空数组

内容的提问来源于stack exchange,提问作者Dileet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.28 09:24:04