简体   繁体   中英

How to handle boolean values itself in the ternary operator or boolean operators?

I am parsing a JSON response and if the data exists I need to return the value as it is, otherwise return null. I tried using ternary operator/boolean operators for this and it works for other datatypes, but not for boolean values itself

Example:

let dummyObj = {
    data: {
        testdata: false
    }
};

console.log(dummyObj.data && dummyObj.data.testdata || null); // returns null always, should return false
console.log((dummyObj.data && dummyObj.data.testdata) ? dummyObj.data.testdata : null); // same behavior, always returns null if the testdata value is false

This statement always returns null as the value of testdata is itself false, it goes into the or condition and returns the null. This works fine if the data is not boolean or the value is true.

How can I make this work? Is there a way to handle boolean values?

Nullish Coalescing operator is a good alternative. This is mostly supported in modern browsers, and optional chaining also help to safely validate your nested properties

console.log(dummyObj?.data?.testdata ?? null); 

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

If you really want to return the value as is if the property exists, then you have to test its existence with the hasOwnProperty method or the in operator:

dummyObject.data?.hasOwnProperty('testdata') ? dummyObject.data.testdata : null
('data' in dummyObject && 'testdata' in dummyObject.data) ? dummyObject.data.testdata : null

If you also want to treat the property as non-existing if it has the values undefined or null , then there are shorter ways as decribed in the other answer.

Another way to phrase this: Determine the exact the range of possible values (or data types) of the property and use the simplest solution that works for that range of values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM