Last active
July 14, 2019 13:38
-
-
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?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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] |
Author
ahmehri
commented
Jul 14, 2019
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment