Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

287
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda