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

如何在JavaScript中合并对象数组同属性值?现有转换代码失效

合并JavaScript对象数组中相同属性名的属性值

输入数组

[
    {
        "attrTitle": "color",
        "attrValue": "Green"
    },
    {
        "attrTitle": "size",
        "attrValue": "M"
    },
    {
        "attrTitle": "size",
        "attrValue": "L"
    },
    {
        "attrTitle": "size",
        "attrValue": "S"
    },
    {
        "attrTitle": "color",
        "attrValue": "Red"
    }
]

期望输出

[
    {
        "attrTitle": "color",
        "attrValue": ["Red", "Green"]
    },
    {
        "attrTitle": "size",
        "attrValue": ["S","L","M"]
    }
]

问题分析

你当前的reduce代码得到的是一个以attrTitle为键、属性值数组为值的对象,并非期望的数组格式。另外如果需要和示例输出一致的属性值排序,还需额外处理排序逻辑。

正确实现

基础实现(不排序)

如果不需要对attrValue排序,只需将reduce生成的对象转换为目标数组格式:

const productAttr = [/* 你的输入数组 */];

const variantAttr = Object.entries(
  productAttr.reduce((acc, { attrTitle, attrValue }) => {
    acc[attrTitle] = acc[attrTitle] ?? [];
    acc[attrTitle].push(attrValue);
    return acc;
  }, {})
).map(([attrTitle, attrValue]) => ({ attrTitle, attrValue }));

带排序的实现(匹配示例输出)

如果需要和示例一致的属性值排序,可在转换时添加排序逻辑:

const productAttr = [/* 你的输入数组 */];

const variantAttr = Object.entries(
  productAttr.reduce((acc, { attrTitle, attrValue }) => {
    acc[attrTitle] = acc[attrTitle] ?? [];
    acc[attrTitle].push(attrValue);
    return acc;
  }, {})
).map(([attrTitle, attrValue]) => ({
  attrTitle,
  attrValue: attrValue.sort()
}));

代码说明

  1. reduce阶段:遍历输入数组,将相同attrTitle的attrValue收集到对应键的数组中,得到形如{ color: ['Green', 'Red'], size: ['M', 'L', 'S'] }的对象。
  2. Object.entries:将上述对象转换为[['color', ['Green', 'Red']], ['size', ['M', 'L', 'S']]]的键值对数组。
  3. map阶段:将每个键值对转换为{ attrTitle: xxx, attrValue: xxx }的对象,得到目标格式数组。
  4. 可选的sort():对attrValue数组进行字典序排序,匹配示例输出的顺序。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 05:41:19