2

This is my code snippet

pastActions = res['data']['list']['names']['blk'].cnt

But I get to see below error

its throws error as Cannot read property 'cnt' of undefined

This is because the parent of cnt is undefined, it might even fail when any of these properties data or list or names or blk is undefined.

I have replaced it as below

res['data'] && res['data']['list] && res['data']['list']['names'] && res['data']['list']['names']['blk'] && res['data']['list']['names']['blk'].cnt ? res['data']['list']['names']['blk'].cnt : '';

and it works, but is there any optimized way to check the same?

Varun Sukheja
  • 6,170
  • 5
  • 51
  • 93
HHH837
  • 31
  • 3
  • well, you could use `.` notation instead, that saves 3 characters per level – Jaromanda X Oct 05 '18 at 09:40
  • Hi @HH837, you can use lodash _.get function. You have an option to return a default value when you have any of the property in the object as undefined. check here: https://lodash.com/docs/4.17.10#get `Gets the value at path of object. If the resolved value is undefined, the defaultValue is returned in its place.` – Eshwar Prasad Yaddanapudi Oct 05 '18 at 09:41
  • `try { pastActions = res.data.list.names.blk.cnt; } catch(e) { }` – Jaromanda X Oct 05 '18 at 09:45

1 Answers1

0

you can use lodash _.get function. You have an option to return a default value when you have any of the property in the object as undefined. check here: lodash.com/docs/4.17.10#get