79561525

Date: 2025-04-08 08:22:38
Score: 1
Natty:
Report link

Adding keys conditionally in 2025

Maybe this is a ES6 thing, but I use Object.create. Since we're way past 2012 and the thread is still relevant, if someone's still looking for a solution to add keys conditionally.

Many times I have encountered a situation where it is preferred that the key is not present itself.

Here's what I use, when I want to have the keys conditionally applied

Object.create({
  someKey: (condition) ? value : undefined,
})

If the condition results to false, then you'll get {} instead of { someKey: undefined }

Reasons:
  • RegEx Blacklisted phrase (1): I want
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: Tanishq Singla