This is my object.
players:{
"ssa": {
"roomCode": "SJRJzaGA8",
"imagesAlloted": [],
"team": "",
"sessionId": "0gSfuhvVF"
},
"ss": {
"roomCode": "SJRJzaGA8",
"imagesAlloted": [],
"team": "",
"sessionId": "8G7QtTEXV"
}
}
I want to iterate whole object with keys and values
I am using
for(let [key, value] in players){
console.log(key + "has" + JSON.stringify(value));
}
this is giving output similar to:
[0] "$" is "c"
[0] "$" is "i"
[0] "t" is "o"
[0] "c" is "l"
[0] "t" is "r"
I am on node version 16.13
I would make my for loop like this
for (let player in players) {
console.log("Key: ", player, " has ", players[player]);
}
player is the key
players[player] will give you the value of that player.
Your way
for (const [key, value] of Object.entries(object1)) {
console.log("Key: ", key, " has ", value);
}
should also give you the same result. Here's the MDN reference https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
The other solutions proposed in this thread work, but I feel OP is making a basic mistake with the syntax of his for/in loop, and it's important for him/her to understand why the initial code failed. It is because there should not be brackets around [key, value]. To do what OP wants with a for/in loop, the syntax is:
for(let p in players){
console.log(p, players[p]);
}
Output:
ssa {roomCode: 'SJRJzaGA8', imagesAlloted: Array(0), team: '', sessionId: '0gSfuhvVF'}
ss {roomCode: 'SJRJzaGA8', imagesAlloted: Array(0), team: '', sessionId: '8G7QtTEXV'}
The reason you got single letters is that your incorrect [key, value] fragment is destructuring each key. When you attempt to destructure a string into an array, the string will break down into individual characters. So given the statement const [foo, bar, baz] = "ABC" will assign A to foo, B to bar, and so on. Your original code iterates over the object, plucks out each key as a string, assigns the first and second letters of that string to variables, and then logs the variables.
Use Object.entries() to get the keys and values.
Object.entries(players).forEach(([key, value]) => console.log(key + "has" + JSON.stringify(value)))