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

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


about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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);
});
about 4 years ago · Juan Pablo Isaza Denunciar

0

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

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