0

我正在尝试返回数组内的对象的值。

const bugSchema = new Schema({
title: {
    type: String,
    required: true
},
 comments:[
    {
        user:{
            type: String,
            required: true
        },
        content: {
            type: String,
            required: true
        }
    }
]

});

我尝试了以下功能,但它没有返回任何内容。

    <% for (bug of bugs) { %>
                        <ion-card>
                            <ion-card-header>
                                <ion-card-title><%= bug.comments.filter(function (value) { value.content }) %></ion-card-title>

                            </ion-card-header>
                            <ion-card-content>

                            </ion-card-content>
                        </ion-card>

                    <% } %>

但是我可以返回一个数组,但它返回整个对象而不是每个对象的值。

          <% for (bug of bugs) { %>
                        <ion-card>
                            <ion-card-header>
                                <ion-card-title><%= bug.comments %></ion-card-title>

                            </ion-card-header>
                            <ion-card-content>

                            </ion-card-content>
                        </ion-card>

                    <% } %>

下面的屏幕截图显示了对象的外观

在此处输入图像描述

我期望实现的是创建一个填充评论内容的离子卡。

4

2 回答 2

1

我认为这会起作用:

<% for (bug of bugs) { %>
  <% for (comment of bug.comments) { %>
    <ion-card>
      <ion-card-header>
        <ion-card-title>
          <%= comment.user %>
        </ion-card-title>
      </ion-card-header>
      <ion-card-content>
        <%= comment.content %>
      </ion-card-content>
    </ion-card>
  <% } %>
<% } %>
于 2019-11-28T15:16:33.423 回答
0
<% bugs.forEach(function(elem) { %>
    <ion-card>
        <ion-card-header>
            <ion-card-title><%= elem.content %></ion-card-title>

        </ion-card-header>
        <ion-card-content>

        </ion-card-content>
    </ion-card>
<% }) %>

这应该可以,我还没有测试过。请记住,Array.filter 返回一个包含通过条件的元素的数组。如果要迭代所有元素,请执行 Array.forEach。

编辑

工作示例:

const ejs = require("ejs");

let post = {
    _id: 123,
    title: "Comments",
    description: "...",
    date: "...",
    time: 15.2,
    assignedTo: "Elon Musk",
    status: "open",
    comments: [
        {
            user: "Elon",
            content: "Test1"
        },
        {
            user: "Elon2",
            content: "Test2"
        }
    ]
};

let render = ejs.render(
    "<% bugs.forEach(function(elem) { %><ion-card><ion-card-header><ion-card-title><%= elem.content %></ion-card-title></ion-card-header><ion-card-content></ion-card-content></ion-card><% }) %>",
    { bugs: post.comments }
);

console.log(render);

//render -> <ion-card><ion-card-header><ion-card-title>Test1</ion-card-title></ion-card-header><ion-card-content></ion-card-content></ion-card><ion-card><ion-card-header><ion-card-title>Test2</ion-card-title></ion-card-header><ion-card-content></ion-card-content></ion-card>

错误应该是post.comments

于 2019-11-28T14:56:58.050 回答