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

如何使用JavaScript提取对象中各元素的serviceCode字段值?

问题分析

你的代码存在三个核心问题:

  1. 对象x中的每个值是JSON字符串,不是可直接访问属性的JavaScript对象,直接push到数组后无法读取carrierCode或serviceCode。
  2. 使用Object.create(x)完全多余,它会创建一个以x为原型的对象,反而增加遍历复杂度,直接遍历原对象x即可。
  3. arr是数组类型,本身没有carrierCode属性,自然返回undefined——你需要遍历数组内的每个解析后的对象,提取对应字段。
解决方案

直接遍历原对象x,将每个JSON字符串解析为对象,然后提取serviceCode并收集:

var x = {
    "0": "{\"carrierCode\":\"ups\",\"serviceCode\":\"ups_ground\",\"packageTypeCode\":\"ups_custom_package\",\"currency\":\"USD\",\"totalAmount\":\"28.66\",\"baseAmount\":\"20.19\",\"surcharges\":[{\"description\":\"Fuel Surcharge Ground\",\"amount\":\"3.28\"},{\"description\":\"Residential Ground\",\"amount\":\"2.01\"},{\"description\":\"Delivery Confirmation Signature\",\"amount\":\"3.18\"}],\"zone\":\"8\",\"quotedWeight\":\"25\",\"quotedWeightType\":\"Actual\"}",
    "1": "{\"carrierCode\":\"ups\",\"serviceCode\":\"ups_second_day_air\",\"packageTypeCode\":\"ups_custom_package\",\"currency\":\"USD\",\"totalAmount\":\"69.72\",\"baseAmount\":\"54.94\",\"surcharges\":[{\"description\":\"Fuel Surcharge - Domestic Air\",\"amount\":\"9.55\"},{\"description\":\"Residential Express\",\"amount\":\"2.05\"},{\"description\":\"Delivery Confirmation Signature\",\"amount\":\"3.18\"}],\"zone\":\"208\",\"quotedWeight\":\"25\",\"quotedWeightType\":\"Actual\"}",
    "2": "{\"carrierCode\":\"ups\",\"serviceCode\":\"ups_next_day_air\",\"packageTypeCode\":\"ups_custom_package\",\"currency\":\"USD\",\"totalAmount\":\"76.62\",\"baseAmount\":\"60.85\",\"surcharges\":[{\"description\":\"Fuel Surcharge - Domestic Air\",\"amount\":\"10.54\"},{\"description\":\"Residential Express\",\"amount\":\"2.05\"},{\"description\":\"Delivery Confirmation Signature\",\"amount\":\"3.18\"}],\"zone\":\"108\",\"quotedWeight\":\"25\",\"quotedWeightType\":\"Actual\"}"
};

// 收集所有serviceCode的数组
var serviceCodes = [];

// 遍历原对象x的每个属性值
$.each(x, function(index, jsonStr) {
    // 将JSON字符串解析为JavaScript对象
    var obj = JSON.parse(jsonStr);
    // 提取serviceCode并加入数组
    serviceCodes.push(obj.serviceCode);
});

// 输出结果
console.log(serviceCodes);
// 输出:["ups_ground", "ups_second_day_air", "ups_next_day_air"]

如果不用jQuery,原生JavaScript可以这样写:

var serviceCodes = Object.values(x).map(jsonStr => JSON.parse(jsonStr).serviceCode);
console.log(serviceCodes);
关键说明
  • JSON.parse():将JSON格式的字符串转换为可操作的JS对象,这是读取serviceCode的前提。
  • Object.values(x):原生方法获取对象所有属性值的数组,替代jQuery的$.each更简洁。
  • map():遍历数组并转换每个元素,直接提取目标字段,代码更紧凑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 07:00:33