Home > OS >  Loop through req.body element, jumps into string when its only 1 Element
Loop through req.body element, jumps into string when its only 1 Element

Time:10-11

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: '[email protected]', role: 'read' },
    { email: '[email protected]', 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?

CodePudding user response:

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 {
  // ...
}
  • Related