[javascript] 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.

This question is related to javascript jquery json

The answer is


Use JavaScript's hasOwnProperty() function:

if (json_object.hasOwnProperty('name')) {
    //do struff
}

No need of JQuery simply you can do

if(yourObject['email']){
 // what if this property exists.
}

as with any value for email will return you true, if there is no such property or that property value is null or undefined will result to false


if you have an array

var subcategories=[{name:"test",desc:"test"}];

function hasCategory(nameStr) {
        for(let i=0;i<subcategories.length;i++){
            if(subcategories[i].name===nameStr){
                return true;
            }
        }
        return false;
    }

if you have an object

var category={name:"asd",test:""};

if(category.hasOwnProperty('name')){//or category.name!==undefined
   return true;
}else{
   return false;
}

if(typeof theObject['key'] != 'undefined'){
     //key exists, do stuff
}

//or

if(typeof theObject.key != 'undefined'){
    //object exists, do stuff
}

I'm writing here because no one seems to give the right answer..

I know it's old...

Somebody might question the same thing..


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?