diff --git a/README.md b/README.md index 5edb186..d406d4b 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ and pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud). -_888 TILs and counting..._ +_889 TILs and counting..._ --- @@ -287,6 +287,7 @@ _888 TILs and counting..._ - [Check If Something Is An Array](javascript/check-if-something-is-an-array.md) - [Check The Password Confirmation With Yup](javascript/check-the-password-confirmation-with-yup.md) - [Computed Property Names In ES6](javascript/computed-property-names-in-es6.md) +- [Conditionally Include Pairs In An Object](javascript/conditionally-include-pairs-in-an-object.md) - [Configure Jest To Run A Test Setup File](javascript/configure-jest-to-run-a-test-setup-file.md) - [Create A Cancelable Promise With PCancelable](javascript/create-a-cancelable-promise-with-pcancelable.md) - [Create An Array Containing 1 To N](javascript/create-an-array-containing-1-to-n.md) diff --git a/javascript/conditionally-include-pairs-in-an-object.md b/javascript/conditionally-include-pairs-in-an-object.md new file mode 100644 index 0000000..9baec28 --- /dev/null +++ b/javascript/conditionally-include-pairs-in-an-object.md @@ -0,0 +1,35 @@ +# Conditionally Include Pairs In An Object + +You can add key-value pairs to an object using the ES6 spread operator: + +```javascript +> { one: 1, ...{ hello: "world" } } +{ one: 1, hello: "world" } +``` + +By combining the spread operator with some boolean logic, you can conditionally +add key-value pairs to an object: + +```javascript +> { + one: 1, + ...(isArriving && { hello: "world" }), + } +``` + +Depending on the value of `isArriving`: + +```javascript +// isArriving === true +{ one: 1, hello: "world" } +``` + +or + +```javascript +// isArriving === false +{ one: 1 } +``` + +This is useful for dynamically building up some configuration object or data +payload.