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

151
Visualizações
check if array of objects includes un object javascript

Each formation contains an array of users and I want to check if one user is part of formation's users. u: the user I want to check if they are part of formation.users. This is my code

 console.log(u)
 console.log(formation.users)
 console.log(formation.users.indexOf(u))

Which u is object and formation.users is array of objects . This is what i see in the console

{ id: 2 }

[ User { id: 2 }, User { id: 3 } ]

-1 We see the array includes the object, why do I obtain this result? Any help please.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

No, you don't see that the array includes the object, you see that the array includes an object with { id: 2 }. Unless it's the exact same object (not some other object that may or may not have the same id property as yours), it won't match:

const a = { id: 1 }
const b = { id: 1 }
const c = b

// Now there exist two objects, both with { id: 1 }.
// The first one is assigned to a, and the second
// one is assigned to both b and c. Therefore, b and c
// are equal, but a isn't equal to either of them.

console.log(a === b) // false
console.log(b === c) // true

Probably you want to check if it contains any object with a matching id instead:

console.log(formation.users.some(user => user.id === u.id))

(This is based on your question to "check if it's included" - if you actually want the index, which is what your existing code suggests that uses indexOf and not includes, then you'd have to use findIndex instead of some.)

about 4 years ago · Juan Pablo Isaza Relatório

0

Each object in javascript is it's own entity. So let a = {id: 1} and let b = {id: 1} in this example a and b are different objects. When you try to do the comparison match with indexOf it follows strict equality, so because they are different object it does not match them.

To achieve what you want to will need to match on one of the inner properties of user.

formation.users.findIndex((user) => user.id === u.id)
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