Skip to content

Instantly share code, notes, and snippets.

@mgmgpyaesonewin
Created January 19, 2018 09:29
Show Gist options
  • Save mgmgpyaesonewin/89213c75be267b468d4f88cafadc5f87 to your computer and use it in GitHub Desktop.
Save mgmgpyaesonewin/89213c75be267b468d4f88cafadc5f87 to your computer and use it in GitHub Desktop.

Conditionally adding keys to JavaScript objects using spread operators and short-circuit evaluation

const buildAnObjectFromAQuery = (query) => { const object = {}; if (query.foo) { object.foo = query.foo; } if (query.bar) { object.bar = query.bar; } return object; } equivalent to

const buildAnObjectFromAQuery = query => ({ ...query.foo && { foo: query.foo }, ...query.bar && { bar: query.bar }, });

as array ...(repeatOn.length > 0) && { repeatOn },

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