W3hobbyist

Snippets and resources for PHP, MySQL, JavaScript-AJAX

Archive for the ‘JavaScript array find if key exists’ tag

Check if key exists or not in a JavaScript array

without comments

Since I work with PHP as well as JavaScript, I know that there is no easy in-built function in JS to check if a given key exists or not in a JavaScript array object. Google-ing for the same returned some user-made functions that were either too long and complicated or even impractical with huge arrays.

The below small snippet works just fine:

[-]View Code JAVASCRIPT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<script type="text/javascript">
//lets setup a sample array and its key-and-values
var array=new Array();
array['name']='Rohan Shenoy';
array['gender']='Male';
array['age']='21';
 
//lets try to find an key which exists
if(array['name']==undefined)
{alert('That key is undefined');}
else
{alert('That keys exists');}
 
//lets try to find an key which does NOT exist
if(array['residence']==undefined)
{alert('That key is undefined');}
else
{alert('That keys exists');}
</script>

As simple as that!

Written by Rohan Shenoy

July 7th, 2008 at 10:59 pm