【问题标题】:Cant Map() Through An Array Of ObjectsCant Map() 通过对象数组
【发布时间】:2021-01-01 11:00:33
【问题描述】:

一段时间以来一直在尝试解决这个问题。 我正在将一个包含对象的数组保存到我的数据库中, 当我尝试通过它 map() 来检索对象的属性时,它只是什么都不渲染。

这是 app.js 代码:

app.get("/:plasticcategory/product/:plasticproduct", (req, res) => {

   const plasticCategory = _.startCase(_.toLower(req.params.plasticcategory));

   const plasticProduct =  req.params.plasticproduct;

   Product.find({category: plasticCategory, title: plasticProduct},'alt', (err, foundItem) => {

     if(err){

       console.log(err)

     }else {

       console.log(foundItem);

      res.render('alternatives', {altProduct: foundItem});

     }

   });

 });

当我 console.log(foundItem) 结果是[ { _id: 5f5f9b2a9f999b1e9009072b, alt: [ [Object] ] } ]

这是我的 ejs 代码(试图呈现 alt 的数组对象属性:

    <% altProduct.map(alt => {%>

     <div class="col-lg-3">

       <h1><%=alt.altTitle %></h1>

       <img src="<%=alt.altImage%>" alt="alt-image">

       <a href="<%=alt.altUrl %>">Get it now!</a>

     </div>

    <% }) %>

我已添加图片以使其更清晰,谢谢enter image description here

【问题讨论】:

  • 尝试console.log(JSON.stringify(foundItem)),以确认foundItem 具有您期望的属性?
  • 是的,它具有我期望的属性,我使用 console.log(JSON.stringify(foundItem) 并通过我的 mongoDB 集群检查了它

标签: node.js arrays object ejs array.prototype.map


【解决方案1】:

当你渲染模板时,我看到你这样称呼它:

res.render('alternatives', {altProduct: foundItem});

其中foundItem 是数组[{ id: 'something', alt: [{ someObject }] }]

这是一个结果数组。这些结果中的每一个都有一个名为“alt”的键,其中包含项目。如果要将所有这些项目一起呈现,则需要将它们全部编译到一个数组中。 (这称为“平面映射”。)

Product.find的回调的else块内部开始:

const itemArrays = foundItem.map(item => item.alt); // Get the inner array from each result
const allAlternativeProducts = [].concat(...itemArrays); // Collect all these products into a single array
  res.render('alternatives', {altProduct: allAlternativeProducts});

【讨论】:

  • 两种解决方案都会出现这个错误:Cannot read property 'map' of undefined
  • @IdanAtias 谢谢,我误解了foundItem 的实际类型。我已经完全更新了我的答案。
  • 非常感谢,但我实际上正在尝试渲染与 URL 指定的类别和标题匹配的每一个“alt”,如果我发布模型的模式会有帮助吗?
  • 好的,每个 'alt' 字段本身就是一个项目列表,每次调用 Product.find 都会检索多个这样的列表。听起来有一个步骤,您需要将这些列表一起收集到一个列表中。
  • 再次改写答案。
猜你喜欢
  • 1970-01-01
  • 2021-06-16
  • 1970-01-01
  • 2021-06-05
  • 2019-05-05
  • 2022-11-27
  • 2020-09-17
  • 2019-07-18
  • 1970-01-01
相关资源
最近更新 更多