为数组的每个元素生成<p>

时间:2019-01-18 15:17:13

标签: node.js

我正在尝试为数组中的每个元素生成一个

,以便可以将其显示在列表中,我尝试了多种方式,例如join()forEach()和其他人,但我没有成功。

app.get("/", (req, res) => {
    db.db()
     .collection("notes")
     .find()
     .toArray(function(e, d) {
       let items = d
     items.forEach(item => {console.log(item)})

     res.end(`<!DOCTYPE html>
    <html>
    <head>
      <meta charset="UTF-8">

      <title>Server</title>
    </head>
    <body>
    <h1> Server running! </h1>
    <ul>
    <p>${JSON.stringify(items.join('</br>'))}</p>
    </ul>
    </body>
    </html>`);
    db.close();
  });

});

我希望每个数组组件看起来像这样: { _id: 5c3f7c25ae62eb0741735d6b,text: '2019-01-16 19:47:01',title: 'Live from an IOT device!' } 将会显示在列表页面中,这就是为什么我尝试添加</br>的原因,如果我使用join()函数,它不是可以工作,但是数组元素显示为对象,而我无法阅读文字。

1 个答案:

答案 0 :(得分:1)

join方法将返回一个字符串,因此它将在其所有元素上调用toString()。由于此处的元素是对象,因此在它们上调用toString()会将其转换为字符串[object Object]。您应该做的是先使用JSON.stringify映射数组,然后然后加入结果:

items = items.map(JSON.stringify);
let output = items.join('<br />');
相关问题