2 hours ago · Tech · hide · 0 comments

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…

No comments yet. Log in to reply on the Fediverse. Comments will appear here.