1

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

1 Answer 1

1

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")
}
Sign up to request clarification or add additional context in comments.

2 Comments

If @nsr knows for sure the JSON will stay like this, I'd go with data.result.usertype === "2". It's always better to use strict equality when you know the type of your variable.
@ValLeNain Yes valid, modified the answer

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.