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

177
Visualizações
Loop through req.body element, jumps into string when its only 1 Element

I have a problem with lopping through my req.body.email. As long as there are minimum 2 emails my obj is printed out like this:

{
  users: [
    { email: 'sadda@gmail.com', role: 'read' },
    { email: 'dsads@web.de', role: 'Admin' }
  ]
}

So everything is correct here. But as soon as I only have 1 email it loops through the individual letters making the obj look like this:

{
  users: [
    { email: 't', role: 'read' },
    { email: 'e', role: 'read' },
    { email: 's', role: 'read' },
    { email: 't', role: 'read' }
  ]
}

This is my code:

router.post('/test/:proID', async (req, res) => {
    const projectID = parseInt(req.params['proID'], 10) || 0;
    var obj = {};
    obj.users = [];
    for (let i = 0; i < req.body.email.length; i++) {
      obj.users[i] = { email: req.body.email[i], role: req.body.right[i]
      };
    console.log(req.body.email.length);
    console.log(req.body.email);
    console.log(obj);

How can I fix this? Also when I have only 1 Email, my req.body.email.length shows the number of letters, instead of the length of the object. So I assume when there's only 1 Email it's just a String and if multiple my req.body.email is an object?

How can I handle this efficiently?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

It seems like the type of the email field in your response body depends on the number of addresses. In case there is only one address, it is a string, if there is more than one address, it's an Array. If you can't change the API to always return an Array, you could check the data type on the client:

if (Array.isArray(req.body.email)) {
  // ...
}
else {
  // ...
}
about 4 years ago · Juan Pablo Isaza 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