不能通过对象数组进行Map

问题描述

现在已经尝试解决这一问题很长时间了。 我正在将包含对象的数组保存到数据库中, 当我尝试通过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

解决方法

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

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

foundItem是数组[{ id: 'something',alt: [{ someObject }] }]的地方。

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

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

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});