如何解决不能通过对象数组进行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] ] } ]
<% 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});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。