Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

let socketId = users.find(u => u.host)?.socketId
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading