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

如何按对象内嵌套的hobbies数组元素对数组分组,实现单个爱好为key的聚合?

你可以通过组合 Lodash 的内置方法实现需求,不需要手动写复杂的遍历聚合逻辑:

const _ = require('lodash')

const result = _.mapValues(
  _.groupBy(
    _.flatMap(arr, ({ name, hobbies }) => 
      hobbies.map(hobby => ({ hobby, name }))
    ), 
    'hobby'
  ),
  group => group.map(item => ({ name: item.name }))
)

逻辑说明

  • 先用_.flatMap把原数组拆为单个爱好对应单个用户的一维数组,每个元素格式为{ hobby: 'biking', name: 'Joe' }
  • 再用_.groupBy按hobby字段对上面的一维数组分组
  • 最后用_.mapValues清洗分组结果,去掉多余的hobby字段,只保留用户信息

如果不想引入 Lodash 依赖,也可以用原生Array.reduce实现,代码同样简洁:

const result = arr.reduce((acc, { name, hobbies }) => {
  hobbies.forEach(hobby => {
    acc[hobby] ||= []
    acc[hobby].push({ name })
  })
  return acc
}, {})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 07:15:04