Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

131
Views
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 answers
Answer question

0

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

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!