简体   繁体   中英

How can I iterate through this object in js?

I'm trying to go through the object of rooms[room] and save all the names with a property side = 1 to one array and names with side = 2 to a different array.

Such as:

side1['tom','bob'];
side2['billy','joe'];

this is what I have so far, it's getting the sides but how do I get the names as well?

var room = '1';
var rooms = {};
rooms[room] = {};

var player = 'tom'
rooms[room][player] = {};
rooms[room][player]['side'] = 1;
var player = 'billy'
rooms[room][player] = {};
rooms[room][player]['side'] = 2;
var player = 'joe'
rooms[room][player] = {};
rooms[room][player]['side'] = 2;
var player = 'bob'
rooms[room][player] = {};
rooms[room][player]['side'] = 1;

for (var key in rooms[room]) {
   if (rooms[room].hasOwnProperty(key)) {
      var obj = rooms[room][key];
      for (var prop in obj) {
         if (obj.hasOwnProperty(prop)) {
            console.log(prop + " = " + obj[prop]);
         }
      }
   }
}

In the code you have, the player names are stored in the variable key during your iterations. Try:

// ...
if (obj.hasOwnProperty(prop)) {
    console.log(prop + " = " + obj[prop]);
    console.log(key); // <- you get the names
}

But IMHO, your code will soon get very messy when you want to have more players. I would suggest having a function that takes care of creating the players and add them to the arrays you want to create during this process. That way you don't have to iterate over the rooms to build the mentioned arrays side1 and side2 .

I would suggest something like this:

var rooms = {};

function newPlayer(roomID, player, side) {
  if ( !rooms.hasOwnProperty(roomID) ) {
    rooms[roomID] = {};
  }
  rooms[roomID][player] = {};
  rooms[roomID][player].side = side;

  if ( !rooms[roomID].hasOwnProperty('side' + side) ) {
    rooms[roomID]['side' + side] = [];
  }
  rooms[roomID]['side' + side].push(player);
}

newPlayer(1, 'tom', 1);
newPlayer(1, 'billy', 2);
newPlayer(1, 'joe', 2);
newPlayer(1, 'bob', 1);

console.log(rooms);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM