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

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

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 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