Home > Software engineering >  How to use find method to search for an object in a function
How to use find method to search for an object in a function

Time:05-24

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);
});


CodePudding user response:

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);
});

CodePudding user response:

Your issue

getUsers() is returning a string but you want to have an array of users, not a string, because a string does not have a method find().

Just remove JSON.stringify() in you method getUsers() and it will work.

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);
  }
  // remove a list instead of a string
  return userList;
}

let users = getUsers();
console.log(users);
const result = users.find((u) => u.id === 0);
if (!result) console.log(`User ${result.id} was not found!`);
else console.log(`User ${result.id} was found!`);

Some remarks

There is no point explicitly calling a function with all parameters as undefined as they will automatically be undefined if you don't provide them, so getUsers() is sufficient.

Your method getUsers() can be made more concise and readable by using the map() function and template strings.

function getUsers(filter, limit, offset) {
  return [...new Array(100)].map((_, index) => ({
    id: index,
    firstname: `firstname_${index}`,
    lastname: `lastname_${index}`,
    email: `${index}@hotmail.com`,
  }))
}

let users = getUsers();
console.log(users);
const result = users.find((u) => u.id === 0);
if (!result) console.log(`User ${result.id} was not found!`);
else console.log(`User ${result.id} was found!`);
.as-console-wrapper { max-height: 100% !important; top: 0; }

  • Related