dimanche 22 mars 2020

JS - Prettier way to check if nested object item has value? [duplicate]

I've got an object with a nested value e.g. item.link.linkInternalRefContainer.linkInternalRef.slug.current

Now, I want to check if current has a value and then I want to populate var link with it's value. Right now I have the following code. It works, but it feels ugly. Plus, what if it lies even deeper? This whole thing is unreadable as it is :)

  if (item.link.linkType === "internalRef") {
    if (item.link.linkInternalRefContainer) {
      if (item.link.linkInternalRefContainer.linkInternalRef) {
        if (item.link.linkInternalRefContainer.linkInternalRef.slug) {
          if (item.link.linkInternalRefContainer.linkInternalRef.slug.current) {
            link =  item.link.linkInternalRefContainer.linkInternalRef.slug.current
          }
        }
      }
    }
  }

The question:

Is there a better, prettier or more efficient way to check if current has a value and then populate link with it? Or to check if current has value by itself.

Aucun commentaire:

Enregistrer un commentaire