Home > Back-end >  Print out Array in Javascript by given name
Print out Array in Javascript by given name

Time:04-10

in my console log i got:

enter image description here

i want to achive a list in my console log like:

michael,klaus

i dont know how to print the JSON object out without the other variables.

server.js:

var arrayUsers=[]

   socket.on('user-connected', (userName_)=>{
        console.log(userName_   " joined "  socket.id)


        arrayUsers.push({
            socket_id: socket.id,
            userName_socket: userName_
        })

        console.log(arrayUsers)

        socket.broadcast.emit('user-connected',userName_)
        socket.emit('online-users',arrayUsers)

        socket.broadcast.emit('online-users',arrayUsers)

    })

index.html:

socket.on('online-users',(arrayUsers)=>{
 
    arrayUsers.forEach(elem=>{
        console.log(elem.userName_socket)
    })
})

CodePudding user response:

You can try using a loop over the array and push each element.username_socket to another array. Then print the new second array.

I hope I was clear. Regards.

CodePudding user response:

arr.forEach(elem=>{
  console.log(elem.userName.socket)
})

You can traverse through the array to get the required elements in a array.

CodePudding user response:

You can map through the array using .forEach

arr.forEach( el => console.log(el.userName_socket))
  • Related