10

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
  • 565
  • 1
  • 7
  • 27
  • 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

5 Answers5

17

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
  • 376,160
  • 25
  • 347
  • 392
8

Use the in operator.

if ( "my property name" in myObject )
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
3
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

Array filter() function

You can use the Javascript array filter funtion. Like that:

const arr = ["ab","cd"]
const needle = "cd"
console.log( arr.filter(i => i == needle).length > 0 ? "exists" : "not exists" )
Max Pattern
  • 1,430
  • 7
  • 18
-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