1

Can this code be simplified to a single assignment? The three variables are inputs I receive from the frontend. I’m using the xss module in Node.js.

var clientname = xss(req.body.clientName, {
    whiteList: [],
    stripIgnoreTag: true,
    stripIgnoreTagBody: ['script']
});
var clientnumber = xss(req.body.clientNumber, {
    whiteList: [],
    stripIgnoreTag: true,
    stripIgnoreTagBody: ['script']
});
var clientaddress = xss(req.body.clientAddress, {
    whiteList: [],
    stripIgnoreTag: true,
    stripIgnoreTagBody: ['script']
});
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
jjpp43
  • 11
  • 1

1 Answers1

1

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:

  1. Use const instead of var.
  2. By convention, JavaScript identifiers use camelCase, not alllowercase.
  3. Cache the object that is being used as the second argument to xss in another variable for reusability and efficiency.
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75