[英]Using pug/jade to iterate over an array of objects
使用帶有 express 的節點,我查詢了我的數據庫並返回了一個對象數組 - 通過控制台記錄數組進行驗證。
我現在需要遍歷對象數組,獲取我需要的鍵/值對並使用 pug 將它們作為列表打印到 html。
Pug 的迭代文檔是這樣說的:
ul
each val in [1, 2, 3, 4, 5]
li= val
在我的 app.js 文件中,這是我用來呈現頁面的代碼:
app.get('/', function (req, res) {
res.render('index', {storeItems: results});
});
在我的 pug 文件中,我使用了這種語法。
.col-6
ul.list-group
each storeItem in storeItems
li.list-group-item storeItem.product_name
運行此代碼會生成以下錯誤。
無法讀取未定義的屬性“長度”。 它說錯誤在這一行:
each storeItem in storeItems
我沒有看到我需要在 pug 文檔中聲明數組長度的位置。 我錯過了什么? 我嘗試將 .length 添加到 storeItems - 生成相同的錯誤。 我試過在 li 后面使用 = 符號,這也會產生同樣的錯誤。
試試這個,
.col-6
ul.list-group
each storeItem in storeItems
li.list-group-item= storeItem.product_name // missed **equal to** operator here
正如@kaysser-kayyali 所說,檢查=。 我有同樣的問題,= 解決了這個問題:
.col-6
ul.list-group
each storeItem in storeItems
li.list-group-item= storeItem.product_name
您需要將返回對象數組轉換為具有單個屬性的對象,該屬性的值為返回對象數組。 在您的示例中,您已將對象數組存儲在數組“storeItems”中。 相反,創建一個對象 {storeItems:[your array of objects here]},然后您的迭代應該可以工作。
另一種可能的解決方案是改變
=
對於
!{foo}
並更改每個語句並添加索引,我總是使用這種結構,它應該可以工作。
示例:
.col-6
ul.list-group
- console.log(storeItems)
each storeItem, index in storeItems
- console.log(storeItem)
li.list-group-item !{storeItem.product_name}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.