单击时将数组项移动到另一个数组

时间:2014-09-25 19:53:29

标签: javascript arrays function addeventlistener

我有两种阵列正在进行

var arrayAdmins = [{"firstName": "Admin", "lastName": "User", "email": "test@1.com","password": "admin"}];
var aBlocked = [{"firstName": "Blocked", "lastName": "User", "email": "test2@2.com","password": "blocked"}]

为了保持这个问题的简单,我有一个按钮:

<input type="button"id="switch">

然后我做一个变量来定位按钮:

 var arraySwitch = document.getElementById('switch');

我想要做的是,当点击按钮时,用户从数组中调用aBlockedarrayAdmins。因此,我希望管理员可以从某个管理面板中删除用户被阻止成为管理员。

2 个答案:

答案 0 :(得分:1)

嗯,您需要有一种方法可以定位要在UI中移动的用户。

然后,只需将用户从一个阵列中移除并将其附加到另一个阵列即可。例如,如果您要删除aBlocked的第二个用户(如果有的话)并将其添加到arrayAdmins,您可以执行以下操作:

var unblockedUser = aBlocked.splice(1, 1)[0];
arrayAdmins.push(unblockedUser);

答案 1 :(得分:1)

您的用户应该有一个“ID”,以便您可以在阵列中识别它们,我认为在您的情况下,该电子邮件是唯一的

var arrayAdmins = [{"firstName": "Admin", "lastName": "User", "email": "test@1.com","password": "admin"}];
var aBlocked = [{"firstName": "Blocked", "lastName": "User", "email": "test2@2.com","password": "blocked"}]

var btnSwitch = document.getElementById('switch');
btnSwitch.onclick = SwitchClicked;

function SwitchClicked(){
    //Remove user from aBlocked
    var removedUser = RemoveUserByEmail(aBlocked, "test2@2.com");

    //Add the removed user to arrayAdmins
    if(removedUser != null){
        arrayAdmins.push(removedUser);
    }
}

//Will remove the first user found with this email and returns it
function RemoveUserByEmail(arrayOfUsers, email){
    for(var i=0; i<arrayOfUsers.length; i++){
        if(arrayOfUsers[i].email === email){
            var removedUsers = arrayOfUsers.splice(i, 1);
            if(removedUsers.length > 0) return removedUsers[0];            
        }
    }

    return null;
}