0

Lets say I'm expecting a variable in a function and if my_var[2].attr[4][2] exists then I can continue with my execution, otherwise something went wrong along the way.

The only way I know how to do this is with the following:

function isdef(x) { return typeof x !== 'undefined'; }

function expects_variable(x) {
    if (isdef(x) && isdef(x.length) && x.length >= 2 && isdef(x[2].attr) && isdef(x[2].attr.length) && x[2].attr.length >= 4 && isdef(x[2].attr[4].length) && x[2].attr[4].length >= 2) {
    //phew, finally!
    }
}

ok maybe a bit absurd example but I have to deal with shorter versions of these all the time.

Essentially, I want to check for the existence of x[2].attr[4][2] without verifying that the whole structure up until that point is valid as well. Is there a way?

user81993
  • 6,167
  • 6
  • 32
  • 64
  • Possible duplicate of [JavaScript, elegant way to check nested object properties for NULL/undefined](http://stackoverflow.com/questions/23808928/javascript-elegant-way-to-check-nested-object-properties-for-null-undefined) – t.niese May 17 '16 at 07:02
  • Possible duplicate of [javascript test for existence of nested object key](http://stackoverflow.com/questions/2631001/javascript-test-for-existence-of-nested-object-key) – JJJ May 17 '16 at 07:03

2 Answers2

0

I feel like after a certain point you might as well just try-catch

try {
   x = my_var[2].attr[4][2]
}
catch (e) {
   // handle and continue
}
Paarth
  • 9,687
  • 4
  • 27
  • 36
  • Depending on how you use the `try-catch` it might be ok to use it that way. If you expect that `my_var[2].attr[4][2]` should exist, then writing the whole code withing the `try-catch` it is valid because you will handle the exception case in the catch block. If you expect that it is likely that `my_var[2].attr[4][2]` might not exist, and if it is about the testing the existence of `my_var[2].attr[4][2]` then it is a _wrong_ usage of `try-catch`. – t.niese May 17 '16 at 07:11
0

This is easily achievable using lodash' get:

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

var object = { 'a': [{ 'b': { 'c': 3 } }] };

_.get(object, 'a[0].b.c');
// → 3

_.get(object, ['a', '0', 'b', 'c']);
// → 3

_.get(object, 'a.b.c', 'default');
// → 'default'

https://lodash.com/docs#get

Robin-Hoodie
  • 4,886
  • 4
  • 30
  • 63