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

176
Views
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 answers
Answer question

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