70 days ago · Tech · hide · Fediverse post

I often encounter situations where I put together an object with conditional properties. The most direct way of doing this is as follows: const author = { name: 'Zell Liew',} if (bio) author.bio = bio This works, but it’s not really nice — because the declaration is split into two places. If we want to keep the declaration in the same place, we can use a conditional spread. This looks funky, but it works. const author = { name: 'Zell Liew', ...(bio && { bio }),} But it feels like we are passing through some JavaScript hoops in order to make this happen. I don’t really like the feeling of that. So I built a function to remove empty values from an object. Then I can simply write the property as if it was already present. // This returns the same results as aboveconst author = omitEmpty({ name: 'Zell Liew', bio,}) What counts as empty I consider the following values to be empty: null undefined An empty string ('') An empty object ({}) An empty array ([]) If a key contains one of these…

Commenting on Bubbles has been removed. Why? If you want to talk about this post, write to the author, use the comments on their blog if it has them, or reply with a "RE:" post on your own blog. Suggestions? feedback@bubbles.town