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

如何将JS对象数组中分散的hobby字段合并为hobbies数组

你可以通过数组map方法结合对象键过滤实现需求,该实现不限制hobby类字段的数量,适配动态字段场景:

const result = array.map(item => {
  // 筛选所有hobby开头的属性值
  const hobbies = Object.entries(item)
    .filter(([key]) => key.startsWith('hobby'))
    .map(([_, value]) => value)
  return {
    name: item.name,
    hobbies: hobbies
  }
})

如果你的hobby字段固定为hobby1~hobby3,也可以用简化写法,性能更高:

const result = array.map(item => ({
  name: item.name,
  hobbies: [item.hobby1, item.hobby2, item.hobby3]
}))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 05:54:05