-2

Here is the code:

if (data.result.parameters.q === undefined ) {
    colsole.log('undefined')
}
//I also tried
if (data.result.parameters.q === null) {
    //   colsole.log('undefined')
// }

Have tried using null and undefined but none works.

dakab
  • 5,379
  • 9
  • 43
  • 67
  • 1
    Do you get an error in the console? If one of the earlier objects in the chain is null it will throw an error. Otherwise you could `console.log(data.result.parameters.q)` and test for whatever it spits out – IrkenInvader Apr 15 '16 at 17:42
  • 1
    `console.log(data.result.parameters.q)` is really undefined? – Hugo S. Mendes Apr 15 '16 at 17:42
  • Typo with `colole` for a start. Also, if any of the parent objects like `parameters` are missing it won't _reach_ `q` to test it, so make sure you test for those too: `if (data && data.result && data.result.parameters && data.result.parameters.q === undefined )...` – Andy Apr 15 '16 at 17:43
  • Also, this has _nothing_ to do with JSON _unless_ you've forgotten to parse some JSON to an object which is also why it would fail the test. – Andy Apr 15 '16 at 17:46
  • Maybe your data object is undefined so you cant ask .result of undefined etc. – luk492 Apr 15 '16 at 17:49
  • See similar question: [javascript test for existence of nested object key](http://stackoverflow.com/questions/2631001/javascript-test-for-existence-of-nested-object-key) – Yogi Apr 15 '16 at 17:49

1 Answers1

1

a === undefined doesn’t necessarily check for undefined since you could set var undefined = {}.

Use either the void or typeof operator (strict equality === isn’t necessary):

if(data.result.parameters.q == void(0) || typeof data.result.parameters.q == 'undefined')
    console.log('data.result.parameters.q is undefined');

How does your data actually look? Are you sure that data, data.result and data.result.parameters are set? There are plenty ways to check, like hasOwnProperty or general truthiness:

if(data.hasOwnProperty('result') && data.result && data.result.hasOwnProperty('parameters'))
    // now we can check if there is q in data.result.parameters

Also note there’s a spelling error in your code: it’s console, not colsole.

dakab
  • 5,379
  • 9
  • 43
  • 67