TIL converting Booleans to Numbers
POSTED ON:
TAGS: helpers javascript
This helper is great for APIs. Not every language parses true/false the same. But every language knows that 0 is false, and 1 is true.
Boolean To Number #
// helper
const booleanToNumber = (object) => {
for (const key in object) {
if (typeof object[key] === "boolean") {
object[key] = object[key] === false ? 0 : 1;
}
}
return object;
};
// example
const user = {
firstName: 'Jar Jar',
lastName: 'Binks',
isJedi: false,
isAlliance: true
}
console.log(booleanToNumber(user));
// {firstName: 'Jar Jar', lastName: 'Binks', isJedi: 0, isAlliance: 1}
Via
7 JavaScript Functions to Master Objects Manipulation and Make Your Code Cleaner
Related TILs
Tagged: helpers