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

149
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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