简体   繁体   中英

Push only if property is defined

Is there a way to fix this condition to remove title from pushing in else part (instead of passing an empty string)?

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

So if the condition in title is not satisfied, I would like to push href only.

Try this

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)

I think you just have to create an if/else condition to check if title is defined like this:

 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 }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM