Pawan
Pawan

Reputation: 32321

How to check if Property exists in JSON and its value is true also

I have got a JSON as follows

{
    "name": "mark",
    "age": 35,
    "isActive": true
}

I need to check if the Property isActive exists and it is true also

I have tried as below its woring ,but wanted to ask is there any better way of doing than below

var test = {
    "name": "mark",
    "age": 35,
    "isActive": true
}

if(test.isActive && test.isActive==true)
{
alert('yes')
}

https://jsfiddle.net/o2gxgz9r/54440/

Upvotes: 0

Views: 3049

Answers (2)

Pranav MS
Pranav MS

Reputation: 2296

You can use json built in function called "hasOwnProperty()" to check this. PLease try like below it is working fine.

var test = {
    "name": "mark",
    "age": 35,
    "isActive": true
}

if(test.hasOwnProperty("isActive") && test.isActive===true){
    alert('yes');
}else{
   alert("no");
}

Upvotes: 3

Barmar
Barmar

Reputation: 780861

Just use

if (test.isActive === true)

If the property doesn't exist, the value of this.isActive will be undefined, which isn't equal to true.

Use === to get strict type checking, so it won't coerce other types and give a false result.

If the property always contains a boolean when it exists, you can just use:

if (test.isActive)

Upvotes: 3

Related Questions