3

I was hoping I could just assign true / false to a variable if my element exists in an associative array.

I tried this --

var finalDisExist = stepsArray['stepIDFinal'];   

-- of course this does exactly what you would think it does (assigning the object to the variable.

But I am pretty sure I have seen something close to this before, can someone tell me what I am missing?

Thanks! Todd

Todd Vance
  • 4,627
  • 7
  • 46
  • 66

4 Answers4

6

Perhaps, the quickest and best way is stepsArray.hasOwnProperty('stepIDFinal').

NB: Do NOT use 'stepIDFinal' in stepsArray, since this will check the entire prototype chain for your "hashmap" object and detect toString among others...

Alexander Pavlov
  • 31,598
  • 5
  • 67
  • 93
  • ...scratch that, you're right. I was thinking of... not sure what. Although checking `'stepIDFinal' in stepsArray` wouldn't be an issue since there's no native `stepIDFinal` property on `Object.prototype`. –  Apr 16 '12 at 18:54
  • @amnotiam: right, yet I believe it's not the only key OP might want to use :) And we've hit this "toString"-ish issue a few times while using the `in` operator. – Alexander Pavlov Apr 17 '12 at 08:02
2

Maybe this?

var finalDisExist = !!stepsArray['stepIDFinal'];

The first negation takes everything that was falsy (like undefined and 0) into true and the second one to real false - and vice versa. This means if stepsArray['stepIDFinal'] is equal to null or 0, finalDisExist will be false...

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
2

You'll want to use stepsArray.hasOwnProperty("stepIDFinal") if I'm not mistaken.

Hacknightly
  • 5,109
  • 1
  • 26
  • 27
1

Do you mean

var finalDisExist = !!stepsArray['stepIDFinal'];

or maybe

var finalDisExist = "undefined" !== typeof stepsArray['stepIDFinal'];

?

Thomas
  • 2,162
  • 1
  • 13
  • 10