I am trying to simplify and shorten my current code. My code is working fine. This is what I have:
app.patch('/listings/:id', (req, res) => {
const { id } = req.params;
console.log(req.body)
const {
leaser, propertyType, pricePerDay,
currency, city, street, description
} = req.body;
const foundListing = listings.find(l => l.id === id);
foundListing.leaser = leaser;
foundListing.pricePerDay = pricePerDay;
foundListing.propertyType = propertyType;
foundListing.currency = currency;
foundListing.city = city;
foundListing.street = street;
foundListing.description = description;
res.redirect('/listings');
})
How can I make the repetitive last half of the code shorter? There is probably a way in which I can write only one line
CodePudding user response:
You can use the spread operator.
app.patch('/listings/:id', (req, res) => {
const { id } = req.params;
console.log(req.body)
const {
leaser, propertyType, pricePerDay,
currency, city, street, description
} = req.body;
const foundListing = {
...listings.find(l => l.id === id),
...req.body
};
res.redirect('/listings');
})
CodePudding user response:
This isn't much shorter, but that's partly because we have it all in one place. If you had a util function to copy these properties, you cna just call it when needed.
Partially applying the functions is entirely down to personal preference
