仅在定义了属性的情况下才推送

时间:2018-09-19 14:13:51

标签: javascript

是否有一种方法可以解决此问题,从而从推入其他部分(而不是传递空字符串)中删除title

photos.push({
    title: (this.display_photos[index].title ? this.display_photos[index].title : ''),
    href: this.display_photos[index].path+this.display_photos[index].name,
});

因此,如果不满足title中的条件,我只想推送href

2 个答案:

答案 0 :(得分:4)

尝试一下

const photo = {
  href: this.display_photos[index].path+this.display_photos[index].name,
}

if (this.display_photos[index].title)
  photo.title = this.display_photos[index].title

photos.push(photo)

答案 1 :(得分:1)

我认为您只需要创建一个if / else条件来检查标题是否定义如下:

const title = this.display_photos[index].title
const href = this.display_photos[index].path+this.display_photos[index].name

if (title) photos.push({ title: title, href: href });
else photos.push({ href: href });

相关问题