如何在js中遍历此对象?

时间:2015-11-10 03:05:32

标签: javascript arrays object

我试图通过房间[房间]的对象并将属性边= 1的所有名称保存到一个数组,并将side = 2的名称保存到不同的数组。

如:

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

这是我到目前为止所获得的,但我如何得到这些名字呢?

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]);
         }
      }
   }
}

1 个答案:

答案 0 :(得分:1)

在您拥有的代码中,播放器名称在迭代期间存储在变量key中。尝试:

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

但恕我直言,当你想拥有更多玩家时,你的代码很快会变得非常混乱。我建议有一个功能,负责创建播放器并将它们添加到您想要在此过程中创建的阵列。这样,您就不必遍历房间来构建所提到的数组side1side2

我会建议这样的事情:

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);