Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there an equalant to PHP array_key_exists in javascript or jquery [duplicate]

Tags:

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?

like image 404
Kanishka Panamaldeniya Avatar asked Aug 02 '12 10:08

Kanishka Panamaldeniya


People also ask

Does array key exist PHP?

PHP array_key_exists() Function The array_key_exists() function checks an array for a specified key, and returns true if the key exists and false if the key does not exist.

How to check array key value in PHP?

The array_key_exists() is an inbuilt function of PHP that is used to check whether a specific key or index is present inside an array or not. The function returns true if the specified key is found in the array otherwise returns false.

How to check if index exists in array PHP?

PHP: Checks if the given key or index exists in an array The array_key_exists() function is used to check whether a specified key is present in an array or not. The function returns TRUE if the given key is set in the array. The key can be any value possible for an array index.

What is array key in PHP?

The array_keys() is a built-in function in PHP and is used to return either all the keys of and array or the subset of the keys. Syntax: array array_keys($input_array, $search_value, $strict) Parameters: The function takes three parameters out of which one is mandatory and other two are optional.


2 Answers

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.

like image 178
Flash Avatar answered Oct 06 '22 04:10

Flash


In Javascript....

if(nameofarray['preferenceIDTmp'] != undefined) {     // It exists } else {     // Does not exist } 
like image 31
Brian Avatar answered Oct 06 '22 03:10

Brian