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

如何在Jade(Pug)模板中读取prices数组内space2的actualPrice属性值

问题核心原因

你传入PUG页面的prices是数组类型,整体结构为:

[
  {"space2":{"actualPrice":"$ 99.990","oldPrice":"$ 129.990","id":11098071}},
  {"h20":{"actualPrice":"$ 69.990","oldPrice":"$ 79.990","id":4444311}},
  {"space":{"actualPrice":"$ 79.990","oldPrice":"$ 99.990","id":4436762}}
]

数组的每个元素才是包含单个商品key(比如space2、h20)的独立对象,因此直接使用prices.space2.actualPrice无法匹配到对应属性。

实现方案

方案1:单独获取space2的actualPrice值

两种写法可选:

  • 已知space2在数组第0位时,可以直接按索引取值:
p space2当前售价:#{prices[0].space2.actualPrice}
  • 不依赖数组顺序的稳妥写法,动态匹配space2属性:
- const targetItem = prices.find(item => item.hasOwnProperty('space2'))
p space2当前售价:#{targetItem.space2.actualPrice}

方案2:正确遍历所有商品展示信息

如果需要遍历所有商品输出对应价格,正确的PUG遍历写法如下:

each productItem in prices
  - const productKey = Object.keys(productItem)[0]
  - const productDetail = productItem[productKey]
  p 商品#{productKey}:当前价#{productDetail.actualPrice},原价#{productDetail.oldPrice}

优化建议

如果可以调整后端接口数据结构,建议直接把prices改成对象类型:

{
  "space2":{"actualPrice":"$ 99.990","oldPrice":"$ 129.990","id":11098071},
  "h20":{"actualPrice":"$ 69.990","oldPrice":"$ 79.990","id":4444311},
  "space":{"actualPrice":"$ 79.990","oldPrice":"$ 99.990","id":4436762}
}

调整后你原本的prices.space2.actualPrice写法就可以直接生效,无需额外处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 17:15:03