【发布时间】:2020-12-11 07:20:02
【问题描述】:
我正在使用 node.js、express、body-parser、ejs、fs 创建一种 api 应用程序。我的服务器正在运行,其他一切正常。问题是有一个已解析的对象(JSON 文件),但在使用我的 index.ejs 模板时我无法访问某些属性:
{
"x":{
"color": "black"
"total": 1
},
"y":{
"color": "red"
"total": 5
}
}
我的 javascrip 文件具有以下循环遍历文件的函数。
var keys = Object.keys(Obj);
for (var i = 0; i< keys.length; i++){
var k = keys[i];
var colorKey = Obj[k].color;
var totalKey = Obj[k].total;
}
var db = keys;
res.render("index", {
db: db
}
然后在我的 index.ejs 上,我的代码适用于第一个属性(“x”和“y”),但无法访问其余部分。
欢迎来到主页!
<% for (var i = 0; i < db.length; i++) { %> ////This is the for loop that shows "x" and "y"
<h1> We have the variable: <%= db[i] %> </h1>
<h1> The color is: <%= db[i].color %></h1>
<h1> There is <%= db[i].total %> left!</h1>
<% } %>
该页面显示了两个变量,但在颜色和总数方面没有显示任何内容。有没有办法在 ejs 中循环它们?
【问题讨论】:
标签: javascript node.js for-loop ejs nested-loops