I have checked this question, adn also this but still my problem persists. I need to store in Mysql in VARCHAR field different data, like true
, false
, numbers and other strings. When I get 'true' or 'false' strings from my DB, in my JS code I need to check that it is boolean
type, hence return true
both for true
and false
values, ore something like typeof Boolean === true
, in other case return false
. I tried many variants from the above mentioned questions, but all solutions returned true
if the value was true
and false
if the values was false
which is wrong for me. Any ideas how to do that would be welcome. Thank you.
Asked
Active
Viewed 151 times
-1

Masha
- 827
- 1
- 10
- 30
-
If I understood correctly, `if (value === "true" || value === "false")`? – user94559 Jun 15 '17 at 08:47
-
yes, maybe there is some more elegant way? – Masha Jun 15 '17 at 08:48
-
What did you try? Show your code and your result please – Duannx Jun 15 '17 at 08:49
-
What do you mean by "more elegant?" This seems like the clearest, most straightforward way to do what you're asking (determine whether the value is one of "true" or "false"). – user94559 Jun 15 '17 at 08:51
-
Do the above if it's a string. If it's coming out of the database as a boolean then just `typeof value === 'boolean'`. – Sam A. Horvath-Hunt Jun 15 '17 at 08:52
-
@SamHH Per the question, it's always a string. (It's a VARCHAR field in the database.) – user94559 Jun 15 '17 at 08:53
-
I'm not sure I got it, from js, you've got Booleans or strings ? Why don't you simply convert all this data into JSON server-side, and then use JSON.parse from js ? – Kaiido Jun 15 '17 at 08:53
-
@smarx, just post it as an answer and I will accept it – Masha Jun 15 '17 at 08:54
2 Answers
1
To determine if the value is one of "true" or "false":
if (value === "true" || value === "false")

user94559
- 59,196
- 6
- 103
- 103
0
You could check the value first, if it should be a boolean and then convert it or return the original value.
value = value === 'true' || value === 'false' ? value === 'true' : value

Nina Scholz
- 376,160
- 25
- 347
- 392