Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

178
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda