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
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/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.