'Print out Array in Javascript by given name
In my console log I got:
I want to achieve a list in my console log like:
michael,klaus
I don't 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)
})
})
Solution 1:[1]
You can try using a .forEach loop over the array and push each elem.userName.socket to another array. Then print the new array.
const arrToPrint= [];
arr.forEach(elem=>{ arrToPrint.push(elem.userName.socket);
})
console.log(arrToPrint);
If you don't care to print each username line by line, replace the .push by a console log.
Solution 2:[2]
arr.forEach(elem=>{
console.log(elem.userName.socket)
})
You can traverse through the array to get the required elements in a array.
Solution 3:[3]
You can map through the array using .forEach
arr.forEach( el => console.log(el.userName_socket))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Christian |
| Solution 2 | |
| Solution 3 | Moiz Sheikh |

