This is an idea for a JavaScript proposal. It would be nice to have a quick way to conditionally add properties to an object literal. More specifically when the value is undefined it is often preferred to not have the property at all in the object. For example:
const value = something();
const obj = { a: 1 };
if (value !== undefined) {
obj.b = value;
}
or
const value = something();
const obj = { a: 1, ...(value ? { b: value } : {}) };
This is very verbose. My proposal is to add a "?" operator to object literals. This operator would only add the property if the value is not undefined. For example:
const value = something();
const obj = { a: 1, b?: value };
If value
is undefined
then obj
would be { a: 1 }
. If value
is not undefined
then obj
would be { a: 1, b: value }
.
Other examples:
const headers = { "Content-Length"?: length };
const obj = { [key]?: value };
Why only undefined
? Because it matches the behavior of JSON serialization. If you serialize an object with JSON.stringify
and the value is undefined
then the property is not included in the JSON string.