Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

278
Views
ExpressJs Trim middleware for nested req.body data

How could I create a middleware to trim all req.body data even NESTED data?

I also accept a trusted well coded package.

Noting that I am using true here : app.use(bodyParser.urlencoded({ extended: true }));

this code ref question

  trim: (req, res, next) => {
    if (req.method === 'POST') {
      for (const [key, value] of Object.entries(req.body)) {
        if (typeof value === 'string') req.body[key] = value.trim();
      }
    }
    next();
  }

This one will work but not for nested data

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

You could loop through each object and array recursively and trim accordingly

function trim(body) {
  for (const key in body) {
    if (typeof body[key] === "object" || Array.isArray(body[key])) {
      trim(body[key]);
    } else if (typeof body[key] === 'string') {
      body[key] = body[key].trim();
    }
  }
};

handleReq: (req, res, next) => {
  if (req.method === 'POST') {
    trim(req.body);
  }
  next();
}
over 4 years ago · Santiago Trujillo Report

0

One way to achieve this in a single line is to utilise the recursion built into JSON.stringify's replacer functionality, check value is number or string then trim it, then parse the result back into an object.

let obj = {
  "a": "f",
  "b": {
    "c": " g",
    "d": "h",
    "x": {
      "a": [
       '1 ', '2 ', '3 '
      ]
    }
  },
  "e": " value3 "
};

obj = JSON.parse(JSON.stringify(obj, (k, v) => ['string', 'number'].includes(typeof v) ? v.trim() : v))

console.log(obj)

Or you could use a recursive function, which if value is object, array then recall the function, lots of example around on that, do a search.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!