Conditional properties with object spread (#tilPost)

Kris Urbas shared a really neat trick to deal with conditional object properties using the object spread operator (currently at proposal stage 3).
const shouldAddProp2 = false;
const obj = {
prop1: 2,
…shouldAddProp2 &&amp…


This content originally appeared on Stefan Judis Web Development and was authored by Stefan Judis

Kris Urbas shared a really neat trick to deal with conditional object properties using the object spread operator (currently at proposal stage 3).

const shouldAddProp2 = false;
const obj = {
  prop1: 2,
  ...shouldAddProp2 && { conditionalProp2: 2 }
}

// it's like
// Object.assign( obj, ( shouldAddProp2 && { conditionalProp2 : 2 } ) );

console.log( obj );

Today this snippet is still hard to read for me, so I have to figure out if I should use this in the future, but it's a neat trick for sure. You can play around with it in the Babel repl.


Reply to Stefan


This content originally appeared on Stefan Judis Web Development and was authored by Stefan Judis


Print Share Comment Cite Upload Translate Updates
APA

Stefan Judis | Sciencx (2017-03-28T22:00:00+00:00) Conditional properties with object spread (#tilPost). Retrieved from https://www.scien.cx/2017/03/28/conditional-properties-with-object-spread-tilpost/

MLA
" » Conditional properties with object spread (#tilPost)." Stefan Judis | Sciencx - Tuesday March 28, 2017, https://www.scien.cx/2017/03/28/conditional-properties-with-object-spread-tilpost/
HARVARD
Stefan Judis | Sciencx Tuesday March 28, 2017 » Conditional properties with object spread (#tilPost)., viewed ,<https://www.scien.cx/2017/03/28/conditional-properties-with-object-spread-tilpost/>
VANCOUVER
Stefan Judis | Sciencx - » Conditional properties with object spread (#tilPost). [Internet]. [Accessed ]. Available from: https://www.scien.cx/2017/03/28/conditional-properties-with-object-spread-tilpost/
CHICAGO
" » Conditional properties with object spread (#tilPost)." Stefan Judis | Sciencx - Accessed . https://www.scien.cx/2017/03/28/conditional-properties-with-object-spread-tilpost/
IEEE
" » Conditional properties with object spread (#tilPost)." Stefan Judis | Sciencx [Online]. Available: https://www.scien.cx/2017/03/28/conditional-properties-with-object-spread-tilpost/. [Accessed: ]
rf:citation
» Conditional properties with object spread (#tilPost) | Stefan Judis | Sciencx | https://www.scien.cx/2017/03/28/conditional-properties-with-object-spread-tilpost/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.