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

如何根据category属性合并对象数组中的同分类项

按category合并对象数组的两种实现方案

一、处理第一种输入格式

输入示例

const input1 = [
  { category: 'Entertainment', 'Hang with Friends': 100 }, 
  { category: 'Entertainment', Chill: 30 }, 
  { category: 'Health', Yoga: 40 },
  { category: 'Health', Birthday: 200 }
];

实现代码

const merged1 = Object.values(input1.reduce((acc, item) => {
  // 解构出category和剩余属性
  const { category, ...rest } = item;
  // 若累加器中无当前category,初始化基础对象
  if (!acc[category]) {
    acc[category] = { category };
  }
  // 合并当前对象的其余属性到对应category的对象中
  Object.assign(acc[category], rest);
  return acc;
}, {}));

输出结果

[
  { category: 'Entertainment', 'Hang with Friends': 100, Chill: 30 }, 
  { category: 'Health', Yoga: 40, Birthday: 200 }
]

二、处理第二种输入格式

输入示例

const input2 = [
  { category: 'Entertainment', subCategory: 'Hang with Friends', price: 100 }, 
  { category: 'Entertainment', subCategory: 'Chill', price: 30 }, 
  { category: 'Health', subCategory: 'Yoga', price: 40 },
  { category: 'Health', subCategory: 'Birthday', price: 200 }
];

实现代码

const merged2 = Object.values(input2.reduce((acc, item) => {
  const { category, subCategory, price } = item;
  // 初始化当前category的基础对象(若不存在)
  if (!acc[category]) {
    acc[category] = { category };
  }
  // 将subCategory作为键,price作为值添加到对应对象中
  acc[category][subCategory] = price;
  return acc;
}, {}));

输出结果

[
  { category: 'Entertainment', 'Hang with Friends': 100, Chill: 30 }, 
  { category: 'Health', Yoga: 40, Birthday: 200 }
]

原代码问题说明

你之前的代码错误在于index[category] ??= category,这里把category字符串直接赋值给了累加器的键,而非初始化一个包含category字段的对象。修正为初始化{ category }对象后,就能正常完成属性合并。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 15:37:28