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

如何按相同sellerId合并数组对象并计算对应产品总价?

问题描述

现有一个动态变化的JavaScript数组info:

const info = [
    {
        productId: "1",
        name: "This is product name 1",
        sellerId: "12",
        price: 30,
    },
    {
        productId: "2",
        name: "This is product name 2",
        sellerId: "12",
        price: 50
    },
    {
        productId: "3",
        name: "This is product name 3",
        sellerId: "13",
        price: 50
    }
]

需要编写函数将其按sellerId合并,得到如下结构的结果数组result:

const result = [
    {
        sellerId: "12",
        productIds: [ // 按相同sellerId合并商品
            {
                name: "This is product name 1",
                productId: "1"
            },
            {
                name: "This is product name 2",
                productId: "2"
            }
        ],
        total: 80 // 这两个商品的总价
    },
    {
        sellerId: "13",
        productIds: [
            {
                name: "This is product name 3",
                productId: "3"
            }
        ],
        total: 50
    }
]
实现方法

可以使用JavaScript的Array.reduce()方法完成分组合并,具体代码如下:

function mergeBySellerId(info) {
    // 用reduce构建以sellerId为键的分组对象
    const groupedData = info.reduce((acc, item) => {
        // 若当前卖家未初始化,创建基础结构
        if (!acc[item.sellerId]) {
            acc[item.sellerId] = {
                sellerId: item.sellerId,
                productIds: [],
                total: 0
            };
        }
        // 提取商品核心信息加入列表
        acc[item.sellerId].productIds.push({
            name: item.name,
            productId: item.productId
        });
        // 累加当前商品价格到总价
        acc[item.sellerId].total += item.price;
        return acc;
    }, {});

    // 将分组对象转换为目标数组格式
    return Object.values(groupedData);
}

// 测试示例
const info = [
    { productId: "1", name: "This is product name 1", sellerId: "12", price: 30 },
    { productId: "2", name: "This is product name 2", sellerId: "12", price: 50 },
    { productId: "3", name: "This is product name 3", sellerId: "13", price: 50 }
];

const result = mergeBySellerId(info);
console.log(result);

代码说明

  1. 分组初始化:遍历原数组时,若当前sellerId未在临时分组对象中,则创建包含sellerId、空商品列表和初始总价0的结构
  2. 商品信息收集:提取每个商品的name和productId,添加到对应卖家的productIds数组
  3. 总价累加:将当前商品的price累加到对应卖家的total字段
  4. 格式转换:通过Object.values()把临时分组对象的所有值提取出来,转换为目标格式的数组

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 22:10:25