31

Possible Duplicate:
Checking if an associative array key exists in Javascript

I have a PHP code block . For a purpose I am converting this to a JavaScript block.

I have PHP

if(array_key_exists($val['preferenceIDTmp'], $selected_pref_array[1]))

now I want to do this in jQuery. Is there any built in function to do this?

Community
  • 1
  • 1
Kanishka Panamaldeniya
  • 17,302
  • 31
  • 123
  • 193
  • http://stackoverflow.com/questions/1098040/checking-if-an-associative-array-key-exists-in-javascript seems to give you a couple of options – JoshuaWohle Aug 02 '12 at 11:02
  • Please refer to this post. http://stackoverflow.com/questions/1098040/checking-if-an-associative-array-key-exists-in-javascript – Vins Aug 02 '12 at 11:02
  • This question is also about numeric array, so, not JSON object. – Peter Krauss Aug 13 '16 at 23:55

3 Answers3

16

Note that objects (with named properties) and associative arrays are the same thing in javascript.

You can use hasOwnProperty to check if an object contains a given property:

o = new Object();  
o.prop = 'exists'; // or o['prop'] = 'exists', this is equivalent 

function changeO() {  
  o.newprop = o.prop;  
  delete o.prop;  
}  

o.hasOwnProperty('prop');   //returns true  
changeO();  
o.hasOwnProperty('prop');   //returns false  

Alternatively, you can use:

if (prop in object)

The subtle difference is that the latter checks the prototype chain.

Flash
  • 15,945
  • 13
  • 70
  • 98
6

In Javascript....

if(nameofarray['preferenceIDTmp'] != undefined) {
    // It exists
} else {
    // Does not exist
}
Brian
  • 8,418
  • 2
  • 25
  • 32
2

http://phpjs.org/functions/array_key_exists:323

This is a great site for PHP programmers moving to js.

Pete
  • 1,289
  • 10
  • 18