Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if key exists in JSON object using jQuery

I have done AJAX validation and validated message is returned as a JSON array. Therefore I need to check whether the keys, like name and email, are in that JSON array.

{     "name": {         "isEmpty": "Value is required and can't be empty"     },     "email": {         "isEmpty": "Value is required and can't be empty"     } } 

Only if the key name is present, I need to write an error message to the name field.

Following is the code to display an error if fields is entered

if (obj['name']'isEmpty'] != "") {                                     $('#name').after(c1 + "<label class='error'>" + obj['name']['isEmpty'] + "</label>"); }                                        if (obj['email']['isEmpty'] != "" ) {     $('#email').after(c4 + "<label class='error'>" + obj['email']['isEmpty'] + "</label>"); } 

But if the name field is entered, it will not be in JSON array. So the checking statement

if (obj['name']['isEmpty'] != "") 

will result in the following error:

obj.name not found


It is not necessary to have key name in the array. At same time I need to check for this to display the error if the array possesses the key name.

like image 900
nidhin Avatar asked Jan 17 '12 10:01

nidhin


People also ask

How to check whether a key exists in object using JavaScript?

Given a JSON Object, the task is to check whether a key exists in Object or not using JavaScript. We’re going to discuss few methods. hasOwnProperty() This method returns a boolean denoting whether the object has the defined property as its own property (as opposed to inheriting it). Syntax: obj.hasOwnProperty(prop) Parameters:

How to check if a certain key or value exists in JSON?

How to check if a certain key or value exists in JSON data using jq? How to check if a certain key or value exists in JSON data using jq? You can use jq in-built function has () and contains () to check if a certain key or value exists in your JSON data.

Is it necessary to have key name in the JSON array?

But if the name field is entered, it will not be in JSON array. So the checking statement It is not necessary to have key name in the array. At same time I need to check for this to display the error if the array possesses the key name. if (json_object.hasOwnProperty ('name')) { //do necessary stuff }

How to check if a value exists in an array?

some () is a JavaScript method that tests a callback function on all the elements of the calling array and returns true if the callback function returns true for any of them. Again, just like with the object, we could also make use of a similar customized reusable function to check a value's existence in an array:


1 Answers

Use JavaScript's hasOwnProperty() function:

if (json_object.hasOwnProperty('name')) {     //do struff } 
like image 96
Dau Avatar answered Sep 18 '22 00:09

Dau