48

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.

4 Answers 4

112

Use JavaScript's hasOwnProperty() function:

if (json_object.hasOwnProperty('name')) {
    //do necessary stuff
}
Sign up to request clarification or add additional context in comments.

3 Comments

it returns false either cases of array has key 'name' nor it doesnt have key 'name'.according to user the fill form the array have elemnts name or email
it return true is key exists and false if not exists
@Dau, for completeness, it actually checks whether the supplied property exists on that object at its link in its prototype chain. Since javascript is prototypical, other objects can extend from other objects by inheriting their prototype. Checking hasOwnProperty ensures you are not "dredging up" items from higher in an object's prototype chain.
18

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

4 Comments

What if the value of email was 0, or false, or an empty string? The property does exist, but this will say it doesn't.
This will also result in a false positive for things like yourObject['toString']. Use hasOwnProperty.
hasownproperty result false despite the name exisit or not
instead of if(obj['name']['isEmpty']!="") use if(obj.hasOwnProperty('name') && obj.name.hasOwnProperty('isEmpty') && obj.name.isEmpty != "")
14
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..

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.