React Next.js中如何访问带动态键名的JSON嵌套对象属性
解决方案:访问动态键下的嵌套属性
核心问题在于shipment下的键是动态变化的UUID,无法通过固定键名直接访问,需要先获取这个动态键对应的对象,再读取price属性。
步骤1:获取动态键对应的Shipment对象
可以通过Object.values()直接提取shipment下的所有值(这里每次请求仅返回一个条目),取第一个元素即可:
// 针对单个quote对象 const shipmentItem = Object.values(quote.groups.group1.shipment)[0]; const price = shipmentItem?.price; // 可选链操作符避免空值报错
也可以用Object.keys()先获取键名,再通过键名访问:
const shipmentKey = Object.keys(quote.groups.group1.shipment)[0]; const price = quote.groups.group1.shipment[shipmentKey]?.price;
步骤2:在React组件中应用(数组遍历场景)
你的代码中使用map遍历quotationDataComplete数组,修改后的完整代码如下:
<span>QuoteId: {quotationData.quoteId}</span> <br /> <br /> {quotationDataComplete.map((quote) => { // 提取动态shipment条目,同时做空值判断 const shipmentEntry = Object.values(quote.groups.group1.shipment)[0]; // 无有效条目时跳过渲染 if (!shipmentEntry) return null; return ( <div className={styles.card} key={shipmentEntry.id}> <span>Price: {shipmentEntry.price}</span> <br /> <br /> </div> ); })}
为什么之前的写法无效?
quote.price:路径错误,price不在quote根节点下quote.shipment.price:路径错误,shipment嵌套在groups.group1内部,且shipment下还有动态键quote.groups.group1.shipment:这是整个shipment对象,不是具体的price值
额外提示:空值安全处理
使用**可选链操作符?.**和空值合并??,可以避免数据未加载或结构异常时的报错:
const price = quote?.groups?.group1?.shipment && Object.values(quote.groups.group1.shipment)[0]?.price ?? 0;
内容的提问来源于stack exchange,提问作者jonas zeferino
相关产品推荐
相关产品推荐

