Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

279
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda