流星检测集合中场的存在
Meteor detecting existence of field in collection
伪代码如下。我的产品结果集有一个可选的图像子数组。我想要做的是在尝试访问 image.href 以用作图像源之前检查产品图像是否存在。在图像不存在的情况下,它每次都会中断。或者,我尝试过 typeof 'undefined',但也没有用。
if (this.products) {
//return "<i class='fa fa-gift'></i>"
console.log("has products");
if (this.products[0].images) { <--- breaks
console.log("item 0 has images");
}
if (this.products.images) { <--- breaks
console.log("has images");
}
} else {
console.log("don't have products");
}
编辑/更新
最终,我认为 Patrick Lewis 对此提供了最佳答案 - 使用混合三元运算符。就像:
myVar = 对象 && object.name || "foo"
如果对象存在并且它有名称,上面会为 myVar 分配名称值,或者...它将分配静态 "foo".
可能this.products
是一个空数组。尝试:
if (this.products && this.products.length) {
var images = this.products[0].images;
if (images && images.length) {
console.log("item 0 has images");
} else {
console.log("item 0 does not have images");
}
} else {
console.log("don't have products");
}
this.products 是您的 collection 还是 MyColl.find() ?
等查询的结果
如果这是查询的结果,您可以这样做:
if (typeof this.products == "object") {
if (typeof this.products.images == "object") { // if images is a property of products and images is an array
// od what you want here
}
}
伪代码如下。我的产品结果集有一个可选的图像子数组。我想要做的是在尝试访问 image.href 以用作图像源之前检查产品图像是否存在。在图像不存在的情况下,它每次都会中断。或者,我尝试过 typeof 'undefined',但也没有用。
if (this.products) {
//return "<i class='fa fa-gift'></i>"
console.log("has products");
if (this.products[0].images) { <--- breaks
console.log("item 0 has images");
}
if (this.products.images) { <--- breaks
console.log("has images");
}
} else {
console.log("don't have products");
}
编辑/更新
最终,我认为 Patrick Lewis 对此提供了最佳答案 - 使用混合三元运算符。就像:
myVar = 对象 && object.name || "foo"
如果对象存在并且它有名称,上面会为 myVar 分配名称值,或者...它将分配静态 "foo".
可能this.products
是一个空数组。尝试:
if (this.products && this.products.length) {
var images = this.products[0].images;
if (images && images.length) {
console.log("item 0 has images");
} else {
console.log("item 0 does not have images");
}
} else {
console.log("don't have products");
}
this.products 是您的 collection 还是 MyColl.find() ?
等查询的结果如果这是查询的结果,您可以这样做:
if (typeof this.products == "object") {
if (typeof this.products.images == "object") { // if images is a property of products and images is an array
// od what you want here
}
}