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

map函数无法读取嵌套数组_s及automate sender2未输出的技术问题

问题分析与修复

核心问题

你的代码存在三个关键问题,导致无法得到预期结果:

  • 错误遍历res对象:使用Object.values(res).map会遍历res的三个属性值(valid_data、shipping_rates、errors),最终生成3条数据,而非valid_data里的2条有效条目。
  • 硬编码固定索引:直接写res.valid_data[0].shipper_name只会取第一个发货人名称,自然看不到automate sender2。
  • 未处理_s字段且存在语法错误:shipping_rates里的对象有重复的reguler键,JS会自动覆盖前一个键值对,导致第一个_s丢失;同时你完全没写提取_s的逻辑。另外之前的TypeError: Object has no member 'map'是因为直接对res对象(非数组)调用数组方法map导致的。

修正后的代码

先修复shipping_rates的重复键问题,再按valid_data的条目数生成目标数据,同时对应提取_s:

const res = {
    "valid_data": [
        {
            "shipper_name": "automate sender1",
            "rts_reasons": ["a reason"],
            "rts_score": 0
        },
        {
            "shipper_name": "automate sender2",
            "rts_reasons": ["a reason"],
            "rts_score": 0
        }
    ],
    // 修复重复键,用数组存储多个运输选项
    "shipping_rates": [
        {
            "reguler_options": [
                {
                    "summary_price": "7.000",
                    "data": [{ "_s": "9917xxx" }]
                },
                {
                    "summary_price": "7.000",
                    "data": [{ "_s": "9918xxx" }]
                }
            ]
        }
    ],
    "errors": [[], []]
}

// 遍历valid_data数组,同时匹配对应索引的_s
const manipulateRequest = res.valid_data.map((item, index) => {
    // 安全提取对应索引的_s,避免不存在时报错
    const sValue = res.shipping_rates[0]?.reguler_options[index]?.data[0]?._s || '无对应值';
    return {
        shipper_name: item.shipper_name,
        _s: sValue
    }
})

const postBulkPayload = {
    "filename": "filename1.xlsx",
    "total_order": manipulateRequest.length,
    "is_use_new_payment": true,
    "template_name": "bulk-order-with-postal_code-and-sub_district_name",
    "details": manipulateRequest,
    "cancelToken": { "promise": {} }
}

console.log(postBulkPayload)

预期输出

{
  filename: 'filename1.xlsx',
  total_order: 2,
  is_use_new_payment: true,
  template_name: 'bulk-order-with-postal_code-and-sub_district_name',
  details: [
    { shipper_name: 'automate sender1', _s: '9917xxx' },
    { shipper_name: 'automate sender2', _s: '9918xxx' }
  ],
  cancelToken: { promise: {} }
}

关键说明

  • 直接遍历valid_data数组,保证生成的条目数和发货人数量一致。
  • 用item.shipper_name获取当前遍历项的发货人名称,自然包含automate sender2。
  • 修复shipping_rates的重复键问题,通过数组存储多个运输选项,再用索引对应到每个发货人条目,正确提取_s。
  • 对数组调用map方法,解决了之前对象不能用map的报错问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 19:19:55