How do I compare string and boolean in Javascript?
I would just explicitly check for the string "true"
.
let data = value === "true";
Otherwise you could use JSON.parse()
to convert it to a native JavaScript value, but it's a lot of overhead if you know it's only the strings "true"
or "false"
you will receive.
var data = true;
data === "true" //false
String(data) === "true" //true
This works fine.
Try expression data == "true"
Tests:
data = "false" -- value will be false
date = "true" -- value will be true
Also, fix your JSON. JSON can handle booleans just fine.
- If one of the operands is a boolean, convert the boolean operand to 1 if it is true and +0 if it is false.
- When comparing a number to a string, try to convert the string to a numeric value.
from MDN Equality Operators page
Examples:
true == "true"; // 1 == NaN → false
true == "1"; // 1 == 1 → true
false == "false"; // 0 == NaN → false
false == ""; // 0 == 0 → true
false == "0"; // 0 == 0 → true