无法通过对象数组进行 Map()
Cant Map() Through An Array Of Objects
一直在努力解决这个问题。
我正在将一个包含对象的数组保存到我的数据库中,
当我尝试通过它 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>
<% }) %>
我添加了图片以使其更清楚,谢谢 <3
enter image description here
当你渲染模板时,我看到你这样称呼它:
res.render('alternatives', {altProduct: foundItem});
其中foundItem
是数组[{ id: 'something', alt: [{ someObject }] }]
.
这是一组结果。这些结果中的每一个都有一个名为 'alt' 的键,其中包含项目。如果你想一起渲染所有这些项目,你需要将它们全部编译成一个数组。 (这叫做'flat-mapping'。)
从 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});
一直在努力解决这个问题。 我正在将一个包含对象的数组保存到我的数据库中, 当我尝试通过它 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>
<% }) %>
我添加了图片以使其更清楚,谢谢 <3 enter image description here
当你渲染模板时,我看到你这样称呼它:
res.render('alternatives', {altProduct: foundItem});
其中foundItem
是数组[{ id: 'something', alt: [{ someObject }] }]
.
这是一组结果。这些结果中的每一个都有一个名为 'alt' 的键,其中包含项目。如果你想一起渲染所有这些项目,你需要将它们全部编译成一个数组。 (这叫做'flat-mapping'。)
从 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});