16

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
Sign up to request clarification or add additional context in comments.

Comments

8

Use the in operator.

if ( "my property name" in myObject )

Comments

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 Comment

good answer, next time add some text to explain.
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" )

Comments

-1

Use hasOwnProperty(key)

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.