我正在尝试从其中具有嵌套数组的Mongo集合中获取JSON对象。我数据库中的plantResult对象看起来像这样:
{
"_id" : ObjectId("5bc97b175c3e221086646b95"),
"username" : "test-user",
"tentname" : "Tent1",
"startdate" : "2018-06-06",
"notes" : "No notes",
"vegnutrients" : "grow1,grow2",
"vegnutrientsvalues" : [
[
{
"_id" : ObjectId("5bc68c91296be70081afdeff"),
"nutrientname" : "grow",
"description" : "Test Grow",
"week1" : 6,
"week2" : 6,
"week3" : 12,
"week4" : 14,
"week5" : 8,
"week6" : 0,
"week7" : 0,
"week8" : 0,
"week9" : 0,
"week10" : 0
}
],
[ ]
],
"growmedium" : "soil"
}
然后我使用EJS和Express在路由器文件中呈现页面,如下所示:
res.render('viewplant', { username: uname, tentname: tentname, resultData: plantResult } );
然后我尝试遍历结果并尝试通过以下方法获取week1
数组中每个项目的vegnutrientsvalues
值:
<script>
var vegnutrients = "<%= resultData[0].vegnutrients %>";
//delimit on comma and add individual nutrients to array
var finalveg = vegnutrients.split(",");
for (var i = 0; i < finalveg.length; i++) {
//WHY CANT IT USE i TO ITERATE THROUGH vegnutrientvalues????
var finalvnd = "<%= resultData[0].vegnutrientsvalues %>";
console.log(finalvnd[i][0].week1);
}
</script>
但是随后控制台读取undefined
,调试器显示以下内容:
var finalvnd = "[object Object],";
console.log(finalvnd[i][0].week1);
但是当我直接像这样获取数据时:
var finalvnd = "<%= resultData[0].vegnutrientsvalues[0][0].week1 %>";
console.log(finalvnd);
它将正确的值记录到控制台,所以我知道数据在那里,我只是不知道如何正确访问它。我想使用for循环中的i
作为索引来获取当前营养素的week1值。有人看到我要去哪里了吗?
答案 0 :(得分:0)
假设您的resultData是一个数组。 resultData [0] .veg Nutritionsvalues 您的veg Nutritionsvalues是嵌套数组,那么在这种情况下,您需要首先循环resultData [0] .veg Nutritionsvalues值,然后遍历 finalveg [i] .length
for (var i = 0; i < finalveg.length; finalvnd = "<%=
resultData[0].vegnutrientsvalues %>";
console.log(finalvnd[i][0].week1);
<% for (var j = 0; j < finalveg[i].length; j++) {%>
}