Home > Enterprise >  how to only return specific property form an array of objects in JavaScript
how to only return specific property form an array of objects in JavaScript

Time:08-28

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

CodePudding user response:

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

CodePudding user response:

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

    return JSON.stringify(outputArray, null, '  ')
  }
  • Related