DEV Community

Cover image for How to conditionally build an object in ES6

How to conditionally build an object in ES6

Knut Melvær on August 13, 2018

I've been tinkering with RSS-feeds for podcasts in CLIs, Express and Serverless functions lately, which involves both parsing and constructing comp...
Collapse
 
kepta profile image
Kushan Joshi • Edited

One of the great pitfalls of using ‘&& ||’ is that you rely on falsy values. It becomes painful when you are dealing with numbers and you have a habbit of simply using the shorthand and “0” gets treated as falsy. For example if I modify your code slightly:

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

let p = episodeParser({id: 0})
p.guid // undefined ! wtf?
Collapse
 
kmelve profile image
Knut Melvær

Ah, the many pitfalls of JavaScript 😅 In this case it id is always a string, but it's good that you point that gotcha out! 👌

Collapse
 
zachkshaw profile image
Zach Shaw

Love this! Nice!