Destructuring and iteration methods are useful for this:
const xssOptions = {
whiteList: [],
stripIgnoreTag: true,
stripIgnoreTagBody: [
"script"
]
},
[
clientName,
clientNumber,
clientAddress
] = [
"clientName",
"clientNumber",
"clientAddress"
].map((property) => xss(req.body[property], xssOptions));
The only thing that changes throughout your assignments is the property name after req.body
, so pass that as an argument to an Array’s map
call, mapping each of those property names to their respective xss
call. Once the xss
calls return, their return values are stored in an array in the same order, then destructured into three separate variables.
Alternatively, you could use an object grouping them all together:
const xssOptions = {
whiteList: [],
stripIgnoreTag: true,
stripIgnoreTagBody: [
"script"
]
},
myXSSObjects = Object.fromEntries([
"clientName",
"clientNumber",
"clientAddress"
].map((property) => [
property,
xss(req.body[property], xssOptions)
]));
console.log(myXSSObjects.clientName);
Additional considerations:
- Use
const
instead of var
.
- By convention, JavaScript identifiers use
camelCase
, not alllowercase
.
- Cache the object that is being used as the second argument to
xss
in another variable for reusability and efficiency.