Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use find method to search for an object in a function

I am stuck to find the user by id using the find function. My this getUsers() function returns an array of objects.

function getUsers(filter, limit, offset) {
  let userList = [];
  for (let i = 0; i < 100; i++) {
    let user = {};
    user.id = i;
    user.firstname = 'firstname_' + i;
    user.lastname = 'lastname' + i;
    user.email = user.userId + "@hotmail.com";
    userList.push(user);
  }
  return JSON.stringify(userList);
}

and I want to find a user by its id here but it shows Data not found:

app.get('/shops/:shopid/users/:userId', (req, res) => {
   let users = getUsers(undefined, undefined, undefined);
   const result = users.find(u => u.id === parseInt(req.params.userId));  
   if(!result) res.status(404).send('Data not found');
   res.send(result);
});


MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Because getUsers returns a JSON string instead of an array. The find method only works on arrays. So you have a few options.

Option 1: Simply return the array in getUSers function

function getUsers(filter, limit, offset) {
  let userList = [];
  for (let i = 0; i < 100; i++) {
    let user = {};
    user.id = i;
    user.firstname = 'firstname_' + i;
    user.lastname = 'lastname' + i;
    user.email = user.userId + "@hotmail.com";
    userList.push(user);
  }
  return userList;
}

Option 2: Use JSON.parse when calling getUsers

app.get('/shops/:shopid/users/:userId', (req, res) => {
   let users = JSON.parse(getUsers(undefined, undefined, undefined));
   const result = users.find(u => u.id === parseInt(req.params.userId));  
   if(!result) res.status(404).send('Data not found');
   res.send(result);
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading