data-point
data-point copied to clipboard
Add method to remove falsy values from objects
Problem description:
I've noticed a pattern of wanting to remove falsy values from objects, but there's no elegant way of doing that:
const reducer = [
input => {
// get the "a" and "b" properties, but only if they're truthy
// this works, but it's awkward and boilerplate-ish
const result = {}
if (obj.a) result.a = a
if (obj.b) result.b = b
return obj
}
]
Suggested solution:
I don't know, but these are a few ideas:
Proposal # 1
const reducer = {
'?a': '$a', // only include this if "$a" is truthy
b: '$b'
}
This works, but we removed the special treatment for keys beginning with '$', so this feels like going backward.
Proposal # 2
// not the best name...
const { removeFalsy } = DataPoint.helpers
removeFalsy({
a: '$a',
b: '$b'
})
This would remove every falsy value, but we might want to keep some of them.
Proposal # 3
// another not-so-great name...
const { truthy } = DataPoint.helpers
{
a: truthy('$a'),
b: '$b'
}
It could work? Feels weird though...
Summary
It would be nice if we don't add a new reducer helper, especially because it would only be useful for object reducers. Not sure if there's a good solution though!