Tyler
Tyler

Reputation: 11509

Shorten repeat assignments with coffeescript

I'm parsing http POST requests with express.js and just need to pull in all the variables that were sent by the client. Right now it looks like this:

token   = req.body.token
amount  = req.body.amount
product = req.body.product
link    = req.body.link
address = req.body.address

Is there a way to shorten these repeat assignments with coffeescript syntax?

Upvotes: 0

Views: 38

Answers (1)

mu is too short
mu is too short

Reputation: 434685

You can use destructured assignment for such things:

Destructuring Assignment
To make extracting values from complex arrays and objects more convenient, CoffeeScript implements ECMAScript Harmony's proposed destructuring assignment syntax. When you assign an array or object literal to a value, CoffeeScript breaks up and matches both sides against each other, assigning the values on the right to the variables on the left.

In your case:

{ token, amount, product, link, address } = req.body

Upvotes: 4

Related Questions