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
.
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(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..
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;
}