nsr nsr - 1 month ago 14
JSON Question

Accessing object from an object

Am trying to access the value of usertype inside result but am not able to do this. I tried something like below, where data am getting is the Below JSON

if(data.result.usertype === 2){
console.log("redirect to type 2 user")
}
else if(data.result.usertype === 3){
console.log("redirect to type 3 user")
}


And the JSON is as below

{
"success": true,
"token": "abc",
"result": {
"_id": "57bd7c857e8d30893a9fc45b",
"usertype": "2",
"created_date": "1472035973314"
}
}

Answer

You should use == , Normaly === is strict type equality operator. It not only checks whether two are equal in value but also of the same type. In your case it is a string,

So use == which just checks only for equality

if(data.result.usertype == 2){
  console.log("redirect to type 2 user")
}

EDIT:

Since you already know the result.usertype is a String, you can stick with the same way and use it as below,

if(data.result.usertype === "2"){
  console.log("redirect to type 2 user")
}
Comments