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

129
Vistas
how to only return specific property form an array of objects in JavaScript

I only want to return the socket id, but forEach returns an undefined value, and find returns the entire object.

I only want the output to be 12345.

const users= [
  { host: true, socketId: "12345" },
  { host: false, socketId: "987654" },
  { host: false, socketId: "5678345" },
];

let socketId = users.forEach((user) => {
  if (user.host === true) {
    return user.socketId;
  }
});//this return undefined 

 let socketId = users.find((user) => {
  if (user.host === true) {
    return user.socketId;
  }
});//this return the whole object {host:true,socketId:"12345"}

    const getHostSocketId = () => {
  for (var i = 0; i < users.length; i++) {
    if (users[i].host === true) {
      return users[i].socketId;
    }
  }
};

   let socketId = getHostSocketId(); //This works, but I'd rather use a method like the ones mentioned above.

   console.log(socketId); //i want this to be 12345
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

let socketId = users.find(u => u.host)?.socketId
about 4 years ago · Juan Pablo Isaza Denunciar

0

let answer = (inputArray) => {
    const outputArray = []
    
    inputArray.forEach((element) => {
      if (element.host === true) {
        outputArray.push(element.socketId)
      }
    })

    return JSON.stringify(outputArray, null, '  ')
  }
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