如何遍历通过客户端上的ejs从数据库传递的对象

时间:2017-12-14 19:45:44

标签: node.js mongodb ejs

我的上一个问题被标记为重复,这是可以理解的,因为我没有解释得太多,所以现在我会更深入地解释它。

这是我的node.js服务器代码,我使用ejs作为我的模板引擎,使用mongo.js连接到我的mongo数据库

server.get('/test', (req,res) => {
    db.surveys.find((err,survey) => {
        res.render('test',{
            survey:survey
        });
    });
});

我的数据库中传递给我视图的对象是

[{
   "surveyCode": 123456,
   "1": {
      "question": "What is your name?",
      "1": {
         "type": "text",
         "placeholder": "Enter your name",
         "header": ""
      }
   },
   "2": {
      "question": "What grade are you in?",
      "1": {
         "type": "radio",
         "content": "9th"
      },
      "2": {
         "type": "radio",
         "content": "10th"
      },
      "3": {
         "type": "radio",
         "content": "11th"
      },
      "4": {
         "type": "radio",
         "content": "12th"
      }
   },
   "3": {
      "question": "What is your gender?",
      "1": {
         "type": "radio",
         "content": "Male"
      },
      "2": {
         "type": "radio",
         "content": "Female"
      },
      "3": {
         "type": "radio",
         "content": "Other"
      }
   }
}]

我已经尝试了一切来尝试遍历对象,因为每个和for循环对我来说都不起作用。如何在视图中迭代对象,以便将每个对象分开并将其存储在变量中。请记住,它是对象中对象的对象,我试图在循环中循环进行循环。

谢谢!

1 个答案:

答案 0 :(得分:0)

以下是一些代码,展示了如何访问对象的内部成员:

var a = [
{
"1":{
"1":{
"type":"text",
"placeholder":"Enter your name",
"header":""
},
"question":"What is your name?"
},
"2":{
"1":{
"type":"radio",
"content":"9th"
},
"2":{
"type":"radio",
"content":"10th"
},
"3":{
"type":"radio",
"content":"11th"
},
"4":{
"type":"radio",
"content":"12th"
},
"question":"What grade are you in?"
},
"3":{
"1":{
"type":"radio",
"content":"Male"
},
"2":{
"type":"radio",
"content":"Female"
},
"3":{
"type":"radio",
"content":"Other"
},
"question":"What is your gender?"
},
"surveyCode":123456
}
];

for(var idx=0; idx < a.length; idx++) {
    var b = a[idx];
    for(var bkey in b) {
        var c = b[bkey];
        for(var ckey in c) {
            var d = c[ckey];
            for(var dkey in d) {
                if (typeof d === 'object') {
                    console.log(dkey);
                    console.log(d[dkey]);
                }
            }
        }
    }
}