JavaScript获取JSON嵌套字段遇报错:Cannot read properties of undefined
问题:无法获取
selling_plan.name的值 我收到的JSON响应如下:
{ id: 41071539879970, properties: {…}, quantity: 1, variant_id: 41071539879970, key: '41071539879970:e0eefb458778bcb81e9efbf1fed9aa6b', final_price: 1100, selling_plan_allocation: { price: 1100, selling_plan: { fixed_selling_plan: false, id: 1079443490, name: "Delivery every 4 weeks" } } }
我先通过以下代码筛选带订阅计划的商品:
const subscriptionProducts = cartResponse.items.filter(item => item.selling_plan_allocation)[0];
因为需要获取item.selling_plan_allocation.selling_plan.name的值,我修改了筛选条件:
const subscriptionProducts = cartResponse.items.filter(item => item.selling_plan_allocation.selling_plan.name)[0];
结果返回undefined。
之后我尝试分两步获取:
const subscriptionProducts = cartResponse.items.filter(item => item.selling_plan_allocation)[0]; const subscriptionName = subscriptionProducts.selling_plan.name
却触发了错误:
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'name')
错误原因
- 第一次筛选失败:
filter回调直接访问item.selling_plan_allocation.selling_plan.name,若某条item存在selling_plan_allocation但缺失selling_plan,会触发隐式错误;且如果name为空值/假值,这条item会被过滤,最终返回undefined。 - 第二次报错:
filter()[0]可能返回undefined(比如数组中无符合条件的item),此时访问subscriptionProducts.selling_plan会因subscriptionProducts为undefined报错;即使存在subscriptionProducts,若其selling_plan_allocation下无selling_plan属性,同样会触发错误。
解决方案
方案1:使用可选链操作符(推荐)
通过?.简化空值检查,同时用find代替filter()[0]提升效率:
// 找到第一个包含有效订阅名称的商品 const targetItem = cartResponse.items.find(item => item.selling_plan_allocation?.selling_plan?.name ); // 安全获取订阅名称,无匹配时返回默认值 const subscriptionName = targetItem?.selling_plan_allocation?.selling_plan?.name || '无订阅计划';
方案2:手动逐层检查
如果环境不支持可选链,可手动判断每一层属性是否存在:
let subscriptionName = '无订阅计划'; const targetItem = cartResponse.items.find(item => { return item.selling_plan_allocation && item.selling_plan_allocation.selling_plan && item.selling_plan_allocation.selling_plan.name; }); if (targetItem) { subscriptionName = targetItem.selling_plan_allocation.selling_plan.name; }
内容的提问来源于stack exchange,提问作者MariaL
相关产品推荐
相关产品推荐

