Skip to content
See Sanity in action 👀 Join us for a live product demo + Q&A →
Sanity
Get started
  • Sanity Studio - Flexible editing environment
  • Content Lake - Real-time database
  • Developer experience - Tooling you love
  • Structured content - The philosophy behind Sanity
  • Review changes - View edits & rollback instantly
  • Image pipeline - On-demand transformations
  • E-commerce - Better shopping experiences
  • Marketing sites - Control your story
  • Products & services - Innovate and automate
  • Mobile apps - Content backend for every OS
  • Aether - Unique digital shopping experience
  • Morning Brew - Omnichannel media distribution
  • InVision - Delivering exceptional customer experiences
  • DataStax - Personalization for global audience
  • React
  • Gatsby
  • Next
  • Nuxt
  • Eleventy
  • Netlify
  • Vercel
  • Algolia
  • Documentation
  • Reference
  • Guides
  • Resource library
  • Headless CMS
  • Tools & plugins
  • Project showcase
  • Schemas & snippets
  • Agency partners
  • Technology partners
  • Get support
  • Share your work
  • 5 Disadvantages Of Wordpress That Are Holding You Back
EnterprisePricing
Contact salesLog inGet started
Published August 13th 2018

How to conditionally build an javascript object with features in

The spread syntax lets you conveniently build an object with optional fields. Especially useful when you move user generated data via APIs to serverless functions.

Knut Melvær

Principal Developer Marketing Manager

I've been tinkering with RSS-feeds for podcasts in CLIs, Express and Serverless functions lately, which involves both parsing and constructing complex objects with lots of fields and information. Since you're dealing with user-generated data from different sources, you aren't guaranteed that all fields are populated all the times. Some fields are optional as well.

Earlier I would deal with this by conditionally applying new keys on an object like this:

function episodeParser(data) {
  const { id, 
  	title,
  	description,
  	optionalField,
  	anotherOptionalField
  } = data
  const parsedEpisode = { guid: id, title, summary: description }
  if (optionalField) {
    parsedEpisode.optionalField = optionalField
  } else if (anotherOptionalField) {
    parsedEpisode.anotherOptionalField = anotherOptionalField
  }
  // and so on
  return parsedEpisode
}

This isn't exactly smooth (but it works). I could also do nifty things with looping the object keys and so on, but that entails code that's a bit more convoluted and you don't get a good sense of what the data object is either.

Yet again, new syntax in ES6 comes to the rescue, and I found a pattern where I was able to rewrite the code over to something like this:

function episodeParser({
  id, 
  title, 
  description = 'No summary', 
  optionalField, 
  anotherOptionalField
}) {
  return {
    guid: id,
    title,
    summary: description,
    ...(optionalField && {optionalField},
    ...(anotherOptionalField && {anotherOptionalField})
  }
}

If we put the function into action, it would look something like this:

const data = { 
  id: 1, 
  title: 'An episode', 
  description: 'An episode summary', 
  anotherOptionalField: 'some data' 
}
episodeParser(data)
//> { guid: 1, title: 'An episode', summary: 'An episode summary', anotherOptionalField: 'some data' }

This function has a couple of features. The first is parameter object destructuring, which is a good pattern if you want to deal with lots of arguments in a function. The second is the three dots spread syntax (...), which here is used to “spread” the object if the condition is true-ish, which we check if the AND operator (&&). What you end up with is a neat concise function which is also easy to test.

You can see it action in our podcast feeds implementation for express.js and netlify lambdas.

Platform

Structured ContentDeveloper experienceContent LakeSanity StudioSecurity & Compliance
  • Sanity vs Contentful
  • Sanity vs Strapi
  • Sanity vs Wordpress
  • Sanity vs Adobe Experience Manager
  • Sanity vs Hygraph
  • Sanity vs Sitecore
  • Sanity vs Storyblok
  • Sanity vs Contentstack
  • Sanity vs Prismic
  • Sanity vs Drupal
  • Sanity vs ButterCMS

Resources

Documentation
  • React Blog
  • Gatsby Blog
  • Next.js Landing Pages
  • Progressive Web Application
  • Single Page Application
  • Svelte & Typescript App
  • Vue & Tailwind Blog
  • Developer Portfolio Templates
  • Form validation with Yup
  • Live Preview with Next.js and Sanity.io
Resource library
  • Agency partners
  • Technology partners
  • Blog Template
  • Personal Website Template
  • Developer Portfolio Templates
  • All Templates
Case Studies
  • Headless CMS
  • What is an API CMS
  • Static Sites 101
  • Headless SEO
  • Localization
  • GraphQL vs REST
  • What is a DXP?
  • Typescript 101
  • Content as a Service
  • Ecommerce SEO
  • React CMS
  • Next.JS CMS
  • CMS for Shopify
  • Content platform
  • Multilingual CMS
  • Static Site CMS
  • Gatsby CMS
  • Node CMS
  • E-commerce CMS
  • Vue CMS
  • Angular CMS
  • GraphQL CMS
  • Newspaper CMS
  • Magazine CMS
  • CMS for apps
  • Remix CMS

Company

Contact SalesEnterpriseCareersTerms of ServiceAccessibility Statement

Stay connected

  • GitHub
  • Slack
  • Twitter
  • YouTube
  • Stack Overflow
  • Blog RSS
  • Newsletter
©Sanity 2023