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

数组值提取与重复ID合并问题求助及Console.log报错排查

问题解决:数组合并重复ID数量值及Console.log报错处理

问题情况

尝试从对象集合中提取值并合并重复ID的qty,但返回结果显示为[object Object];同时使用Console.log输出时出现报错:

Error: org.mozilla.javascript.EcmaError: ReferenceError: "Console" is not defined. (threadScript#1)

输入代码(原错误版本)

tempOut = { ID: "7283", qty: 60.52 },
    { ID: "7280", qty: 3.75 },
    { ID: "7283", qty: 16 }

var array = [
    temphours
    ];

var result = [];
array.reduce(function(res, value) {
    if (!res[value.Id]) {
        res[value.Id] = { Id: value.Id, qty: 0 };
        result.push(res[value.Id])
    }
    res[value.Id].qty += value.qty;
    return res;
}, {});

期望输出

合并后的对象数组:

result = [
    { ID: "7283", qty: 76.52 },
    { ID: "7280", qty: 3.75 }
]

最终期望格式

7283, 76.52
7280,3.75

解决方案

1. 修复基础语法与变量错误

原代码存在多处语法和变量问题:

  • tempOut定义错误:多个对象直接用逗号分隔不是合法数组,需要用[]包裹成数组
  • 变量名错误:temphours未定义,应该使用tempOut
  • 键名大小写不一致:对象中是ID(大写D),但代码中误用value.Id(小写d),需统一为ID

2. 实现重复ID的qty合并逻辑

修正后的合并逻辑代码:

// 正确定义对象数组
const tempOut = [
    { ID: "7283", qty: 60.52 },
    { ID: "7280", qty: 3.75 },
    { ID: "7283", qty: 16 }
];

const array = tempOut; // 直接使用定义好的数组
const result = [];

array.reduce(function(res, value) {
    // 统一使用大写ID作为键名
    const id = value.ID;
    if (!res[id]) {
        res[id] = { ID: id, qty: 0 };
        result.push(res[id]);
    }
    res[id].qty += value.qty;
    return res;
}, {});

3. 转换为最终期望的文本格式

遍历合并后的result数组,生成指定格式的字符串:

const finalOutput = result.map(item => `${item.ID}, ${item.qty}`).join('\n');
// 输出结果
print(finalOutput); // 使用print适配Rhino环境

4. 解决Console.log报错问题

  • 报错原因:Rhino环境中没有大写的Console对象,正确写法是小写的console.log()
  • 若console.log仍不可用,Rhino环境默认支持print()方法用于输出,直接替换即可

完整运行代码

const tempOut = [
    { ID: "7283", qty: 60.52 },
    { ID: "7280", qty: 3.75 },
    { ID: "7283", qty: 16 }
];

const array = tempOut;
const result = [];

array.reduce(function(res, value) {
    const id = value.ID;
    if (!res[id]) {
        res[id] = { ID: id, qty: 0 };
        result.push(res[id]);
    }
    res[id].qty += value.qty;
    return res;
}, {});

// 转换为最终格式并输出
const finalOutput = result.map(item => `${item.ID}, ${item.qty}`).join('\n');
print(finalOutput);

运行结果

7283, 76.52
7280, 3.75

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 00:52:40