15

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!

1

5 Answers 5

21

With in operator.

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

'a' in { a: 'foo' } // true
'b' in { a: 'foo' } // false
8

Use the in operator.

if ( "my property name" in myObject )
4
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
  • 1
    good answer, next time add some text to explain.
    – Eldshe
    Commented Mar 1, 2021 at 16:10
2

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" )

-1

Use hasOwnProperty(key)

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.