从多维数组或对象中移除元素



我有一个rooms对象,在该对象中有许多rooms数组,每个room中都有users元素。

var rooms = {"room1":["user1","user2"],"room2":["user1","user2","user3"]};

如何编写一个函数,当调用时从房间数组中删除特定的用户?

function leaveRoom(user,room){
  if(typeof room != "undefined"){
//remove user from the specific room ONLY if room argument is passed
  } else {
//remove user from all rooms    
  }
}

我已经尝试使用splice与元素的索引,但它不工作。

Array.prototype.remove = function(value) {
    if (this.indexOf(value)!==-1) {
       this.splice(this.indexOf(value), 1);
       return true;
   } else {
      return false;
   };
} 
var roomName="room1",
    userName="user1";
rooms[roomName].remove(userName);

实际上我甚至不确定它是对象还是数组了。请帮忙,谢谢

您可以使用for..in循环,delete, Array.prototype.filter()从数组中删除值为undefined的元素

var rooms = {
  "room1": ["user1", "user2"],
  "room2": ["user1", "user2", "user3"]
};
function leaveRoom(user, room, obj) {
  if (room && Array.isArray(obj[room])) {
    delete obj[room][obj[room].indexOf(user)];
  } else {
    for (var prop in obj) {
      delete obj[prop][obj[prop].indexOf(user)];
    }   
  };
  for (var prop in obj) {
      obj[prop] = obj[prop].filter(Boolean)
  }
}
leaveRoom("user1", "room1", rooms);
console.log(rooms); // remove `"user1"` from `"room1"`
// pass `null` as second parameter to remove `user` from all rooms
leaveRoom("user2", null, rooms); // remove `"user2"` from all rooms
console.log(rooms);

我使用for..in循环和slice。希望这对你有帮助

    var rooms = {
  "room1": ["user1", "user2"],
  "room2": ["user1", "user2", "user3"],
  "room3": ["user1", "user2", "user3"]
};
function leaveRoom(user, room) {
  for (var eachroom in rooms) {
    if (eachroom == room) {
      var users = (rooms[eachroom]);
      for (var user_index in users) {
        if (users[user_index] == user) {
          users.splice(user_index, 1);
          break;
        }
      }
      rooms[eachroom] = users;
      break;
    }
  }
  //checking whether the user is removed
  for (var i in rooms) {
    var j = (rooms[i]);
    alert(i+":"+j);
  }
}
leaveRoom('user2', 'room3');

链接到jsfiddle: https://jsfiddle.net/kannanore/s6u6m5fn/3/

相关内容

  • 没有找到相关文章

最新更新