Meteor正在检测集合中是否存在字段

Meteor detecting existence of field in collection

本文关键字:是否 存在 字段 集合 检测 Meteor      更新时间:2023-09-26

下面的伪代码。我的产品结果集合有一个可选的图像子阵列。我想做的是在尝试访问image.href用作图像源之前,检查产品是否存在图像。在图像不存在的情况下,它每次都会中断。另外,我也尝试过"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");
        }

编辑/更新

最终,我认为帕特里克·刘易斯提供了最好的答案——使用混合三元算子。类似于:

myVar=对象&amp;对象名称||"foo"

如果对象存在并且它有一个名称,或者。。。它将分配静态"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是您的集合还是像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
  }
}