0

Here is my exact code:

   <Text style={styles.priceText} numberOfLines={2}>
          {'$ '+item.right.detail ? item.right.detail.price: ''}{'\n'}{'\n'}
   </Text>

So sometimes it's possible that item.right.detail is null or perhaps undefined. This check is not working. I get an error undefined is not an object (evaluating item.right.detail)

I need a way to be able to construct strings of data from object elements where some of those sub objects or values could be null. Obviously I want to do this without crashing!

Do I have to do something crazy like:

  private getPrice(item){
      var retVal = '$';
      if (typeof item !== 'undefined' ) && (item)) {
         if (typeof item.right !== 'undefined' ) && (item.right)) {
          if (typeof item.right.detail !== 'undefined' ) &&  (item.right.detail)) {

           if (typeof item.right.detail.price !== 'undefined' ) && (item.right.detail.price)) {
              retVal = retVal+item.right.detail.price;
          }  
       }    
    }
 }
 return retVal;
}
gitsensible
  • 551
  • 1
  • 8
  • 19
  • 1
    Try AND condition : {'$ '+ item.right && item.right.detail ? item.right.detail.price: ''}{'\n'}{'\n'} – Ved May 17 '17 at 04:08
  • I think it will still crash if item.right is undefined. But I will try it. – gitsensible May 17 '17 at 04:15
  • No It will not crash. If Item is undefined than It will crash. – Ved May 17 '17 at 04:24
  • Ok now I tried: {'฿ '+ item.right && item.right.detail ? item.right.detail.price: ''}{'\n'}{'\n'} but I get 'undefined is not an object (evaluating 'item.right.detail') So I need to check both item.right and item.right.detail are both not undefined. Not sure how to nest this check. – gitsensible May 17 '17 at 04:28
  • Use lodash as outlined in http://stackoverflow.com/questions/6393943/convert-javascript-string-in-dot-notation-into-an-object-reference – gitsensible May 17 '17 at 04:49

2 Answers2

0

Try using !! operator. For null values, !! returns false, so, your code could be something like this:

<Text style={styles.priceText} numberOfLines={2}>
      {'$ '+ (!item || !item.right || !item.right.detail || !item.right.detail.price) ? '' : item.right.detail.price}{'\n'}{'\n'}
</Text>
Sergio D.
  • 46
  • 3
  • if `item.right` is undefined, then this will not work anyway, because we can't take .detail out of undefined... – Lojka May 17 '17 at 04:27
  • I will try it. However, I think this is probably a place for lodash library which is probably implemented very similar to what you have. – gitsensible May 17 '17 at 04:55
0

I think the problem can best be solved by lodash library.

see https://lodash.com/docs#get _.get(object, path, [defaultValue])

Gets the value at path of object. If the resolved value is undefined, the defaultValue is returned in its place.

_.get(item, "item.right.detail.price", 'Not available') // This should work.

gitsensible
  • 551
  • 1
  • 8
  • 19