• Register
1 vote
65 views

Problem:

I just jump into the JavaScript learning process. I am grabbing the language day by day gradually. I want to declare an object or an array in my code and check whether the key is available or not in it.  So, let me put my question this way, in javascript check if key exists in array?

I’d really appreciate your effort and help. Thanks a lot, mate.

12 7 7
15,250 points

Please log in or register to answer this question.

1 Answer

1 vote
 
Best answer

Solution:

There are several ways to check if the keys exist in an object or array in JavaScript.

For objects, you can use the in operator to check the keys’ existence. This is a boolean type operator and throws back a True/False output

let myobj = {
   name: "Roy",
   age: 25
   id: 01
}
console.log('name' in myobj);
console.log('address' in myobj);
console.log('id' in myobj);

Output will be

true
false
true

For the case of an array, you can use the indexOf() method. This method returns -1 if the key doesn’t exist in the array else it returns the index of the array.

let myarr = ["Roy", 5, 2, "John", 23.5];
console.log(myarr.indexOf({}))
console.log(myarr.indexOf("Roy"))
console.log(myarr.indexOf(23.5))

And the output it throws is

-1
0
4

 

13 9 6
94,260 points

Related questions

0 votes
1 answer 8 views
8 views
Problem: I have tried all of the solutions suggested and still not be able to fix the problem. Please help me with some advice.
asked Apr 1 zayed1 61.8k points
0 votes
1 answer 687 views
687 views
I am new to this. I just want to know how to do that?
asked Nov 28, 2020 TeamScript 13.5k points
0 votes
1 answer 17 views
17 views
Problem: Is there anyone who can help me so i can run my code to check if a key exists in a javascript object please help me. How can I check if a specific key exists in a JavaScript object or array? If the key doesn't exist and I try to access it, will it return false? Or throw a mistake?
asked Nov 10, 2020 Han Li 710 points
0 votes
1 answer 5 views
5 views
Problem: How do I determine whether an array contains a value?
asked Apr 19 sumaiya simi 43.9k points
0 votes
1 answer 7 views
7 views
Problem: Can you please the solution of it? Javascript check if object exists in array
asked Apr 2 Ifra 36.4k points
0 votes
1 answer 32 views
32 views
I was working on that. I just want to know how to do that?
asked Nov 7, 2020 TeamScript 13.5k points
0 votes
1 answer 47 views
47 views
I am new to this. I just want to know how to do that ?
asked Nov 3, 2020 TeamScript 13.5k points
1 vote
1 answer 3 views
3 views
Problem: How to fix this error : javascript check if key in object
asked Mar 25 MUHAMMAD MUNEEB 83k points
1 vote
1 answer 6 views
6 views
Problem: Please help me. How can I solve it? javascript check if object has key
asked Mar 25 MUHAMMAD MUNEEB 83k points
0 votes
1 answer 8 views
8 views
Problem: Have you any idea how I could solve this problem? Thank you so much! Thank you very much!
asked Apr 1 zayed1 61.8k points