9

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!

Dilip Kumar Yadav
  • 535
  • 1
  • 6
  • 26
  • 2
    Possible duplicate of [Checking if a key exists in a JavaScript object?](http://stackoverflow.com/questions/1098040/checking-if-a-key-exists-in-a-javascript-object) – Harsh Sanghani Dec 07 '15 at 11:16

4 Answers4

16

With in operator.

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

'a' in { a: 'foo' } // true
'b' in { a: 'foo' } // false
Nina Scholz
  • 351,820
  • 24
  • 303
  • 358
7

Use the in operator.

if ( "my property name" in myObject )
Quentin
  • 857,932
  • 118
  • 1,152
  • 1,264
2
let $arr = [1, 0, false];

console.log($arr.indexOf(0));     // 1
console.log($arr.indexOf(false)); // 2
console.log($arr.indexOf(15));    // -1

if ($arr.indexOf(18) !== -1) //Todo
-1

Use hasOwnProperty(key)

for (let i = 0; i < array.length; i++) {
        let a = obj[i].hasOwnProperty(`${key}`);
        if(a){
            console.log(obj[i])
       }
    }
cohen chaim
  • 1
  • 1
  • 2