删除嵌套在Object中的关联数组值

时间:2013-12-18 23:41:30

标签: javascript arrays object

DEMO FIDDLE

我的工作方案有以下结构。

Object {room1: Array[2], room2: Array[3], room3: Array[1]}

我正在使用以下方法添加值:

function addValue(obj, key, value, socketId) {
if (obj.hasOwnProperty(key))
    obj[key].push({socketid: socketId, user: value});
else 
    obj[key] = [{socketid: socketId, user: value}];
}

现在我想从Array中删除特定的行条目。因此,要知道所有三个字段 - obj, key and value,请从数组中删除此特定内容。

所以,例如,如果我有

addValue(online, "room1","userA1","sA1");
addValue(online, "room1","userA2","sA2");
addValue(online, "room2","userB1","sB1");
addValue(online, "room2","userB2","sB2");
addValue(online, "room2","userB3","sB3");
addValue(online, "room3","user3","s3");

类似的东西:

{ 
    room1: {socketid : sA1, user: userA1},
           {socketid : sA1, user: userA1},
    room2: {socketid : sB1, user: userB1},
           {socketid : sB2, user: userB2},
           {socketid : sB3, user: userB3},
    room3: {socketid : s3,  user: user3}
}

现在我要删除键= sB2且值= userB2的行。

所以 HOW TO 最终有类似的东西:

{ 
    room1: {socketid : sA1, user: userA1},
           {socketid : sA1, user: userA1},
    room2: {socketid : sB1, user: userB1},
           {socketid : sB3, user: userB3},
    room3: {socketid : s3,  user: user3}
}

DEMO FIDDLE

1 个答案:

答案 0 :(得分:1)

例如

function deleteValue(obj, key, value, socketId) {
    if (!obj.hasOwnProperty(key))
        return;
    obj[key] = obj[key].filter(function(x) {
        return x.user != value || x.socketid != socketId
    })
}

http://jsfiddle.net/k3McA/1/