You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何不使用lodash等库实现按key分组的对象数组转换

实现代码

你可以结合Array.reduce()和Object.values()完成转换,无需引入第三方库,示例如下:

// 遍历原数组生成分组映射
const groupMap = foosWithBar.reduce((acc, foo) => {
  const barId = foo.bar.id
  // 不存在对应分组时先初始化
  if (!acc[barId]) {
    acc[barId] = { id: barId, foos: [] }
  }
  // 插入当前foo信息到对应分组
  acc[barId].foos.push({ id: foo.id })
  return acc
}, {})

// 将映射对象的值转为数组,得到目标结果
const barsWithFoos = Object.values(groupMap)

上述代码运行后输出的barsWithFoos和你给出的预期结构完全一致。

如果需要适配更多场景,可封装为通用方法:

/**
 * 数组分组转换
 * @param {Array} arr 原数组
 * @param {Function} getGroupKey 分组键生成函数
 * @param {Function} transformItem 子项转换函数
 * @returns 分组后的数组
 */
const groupBy = (arr, getGroupKey, transformItem) => {
  const map = arr.reduce((acc, item) => {
    const key = getGroupKey(item)
    if (!acc[key]) acc[key] = { id: key, items: [] }
    acc[key].items.push(transformItem(item))
    return acc
  }, {})
  return Object.values(map)
}

// 调用示例
const barsWithFoos = groupBy(
  foosWithBar,
  item => item.bar.id,
  item => ({ id: item.id })
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 07:12:02