Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a key exists in javascript array?

Tags:

javascript

How can i check if a particular key exists in a JavaScript array?

Actually, i am checking for undefinedness for whether a key exists. What if the key exists but the value is actually undefined?

var obj = { key: undefined }; obj["key"] != undefined // false, but the key exists!

like image 501
Dilip Kumar Yadav Avatar asked Dec 07 '15 11:12

Dilip Kumar Yadav


2 Answers

With in operator.

0 in [10, 42] // true
2 in [10, 42] // false

'a' in { a: 'foo' } // true
'b' in { a: 'foo' } // false
like image 176
Nina Scholz Avatar answered Sep 28 '22 08:09

Nina Scholz


Use the in operator.

if ( "my property name" in myObject )
like image 38
Quentin Avatar answered Sep 28 '22 07:09

Quentin