DEV Community

Discussion on: The shortest way to conditional insert properties into an object literal

Collapse
 
willsmart profile image
willsmart • Edited

That's awesome. Thanks for posting.
I didn't know that the rest operator could take an expression (though it does make sense).

I think your example could be better though. As said you'd quickly run into unexpected behaviour with falsey primitive values, which you mention but downplay. It's a showstopper imo.
As a shortened, silly example showing what could happily ruin your day in longer, serious code...

wrappedStringLength  =  string => ({...string&&{string}}.string.length)
wrappedStringLength('a')
>> 1
wrappedStringLength('')
>> Uncaught TypeError: Cannot read property 'length' of undefined

Most coders would assume a method would treat an empty string like any other.

I'd just code the example object as...

{
    state, priority,
    collection: 'Cats',  
    sort: 'asc',
}

Just simpler and less brittle.

A better example might use something where the inserted properties are computed. a la...

userObject  =  ({id, name, type, age}) => ({
  name, age, type,
  ... type=='prof' && { gradStudents: fetchGradStudentsForProf(id)  }
  ... type=='roofer' && { jobs: fetchJobsByRoofer(id) }
})
Collapse
 
jfet97 profile image
Andrea Simone Costa

I think you will understand that this is beyond the scope of the article.
My first point was to show a nice, little know js fact. The second was to explain why such code is allowed.
All the rest is left to the reader's good will and curiosity :D