Skip to content

Instantly share code, notes, and snippets.

@ahmehri
Last active July 14, 2019 13:38
Show Gist options
  • Save ahmehri/17d9646f74fc316e5915f43137942164 to your computer and use it in GitHub Desktop.
Save ahmehri/17d9646f74fc316e5915f43137942164 to your computer and use it in GitHub Desktop.
How to conditionally add a property to an object, using an object literal, only when its value is defined?
let result;
let value;
result = {
value
};
// how to avoid the following result, adding a property to an object
// if it's value is undefined?
result;
// by using if block
value = undefined;
result = {};
if (typeof value !== "undefined") {
result.value = value;
}
result;
// using if block works, but what if we want to do the same logic in a declarative
// way, i.e when using an object literal? the solution is to use destructuring.
// this relies on the fact that undefined destructuring works in an object, see
// below
const useDestructuring = value => ({
...(typeof value === "undefined" ? undefined : { value })
});
result = useDestructuring(undefined);
result;
result = useDestructuring("value");
result;
// destructuring undefined
result = { ...undefined }
result
result = [...undefined]
@ahmehri
Copy link
Author

ahmehri commented Jul 14, 2019

Screenshot 2019-07-14 at 15 17 51

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment