从数组返回对象时排除属性?

时间:2014-09-20 22:07:26

标签: javascript object

var users = [
    {name: tim, password: 123, connected: true}, 
    {name: jim, password: 345, connected: true}, 
    {name: kim, password: 678, connected: true, admin: true}, 
    {name: pim, password: 91011}
];

var connectedUsers = users.filter(function( connectedUser ) {
    if(!connectedUser.admin) {
        return connectedUser.connected;
        //not sure how to return the connected users object without the password attr
    }
});

以上回复所有连接的用户,这是为我的应用程序构建一个api,只有管理员可以访问此路由并且密码已加密但我想将它们从请求中排除。那么如何通过排除密码attr来过滤对象?

3 个答案:

答案 0 :(得分:1)

filter()用于过滤条目;即,如果您为某个条目返回true,则它将包含在结果中,否则将被删除。因此,您无法使用filter()转换输入。相反,您应将map过滤后的结果发送到没有密码的对象:

var users = [
    {name: 'tim', password: '123', connected: true}, 
    {name: 'jim', password: '345', connected: true}, 
    {name: 'kim', password: '678', connected: true, admin: true}, 
    {name: 'pim', password: '91011'}
];
users.filter(function( connectedUser ) {
    return !connectedUser.admin && connectedUser.connected;
}).map(function(user) {
    // return {name: user.name, connected: user.connected}
    // __OR__
    // EDIT1: You can as the following to delete only one
    // field if the user object is very large. You can also
    // use JQuery's clone() method instead of stringify/parse.
    userCopy = JSON.parse(JSON.stringify(user))
    delete userCopy.password
    return userCopy
})

PS。我对你的过滤功能进行了微小的改动。

答案 1 :(得分:1)

您应该 map 过滤数组,从每个元素中删除密码。您可以通过创建没有密码属性的新用户对象来完成此操作:

var connectedUsers = users.filter(function(user) {
    // ...
})
.map(function(user) {
    var newUser = {}, key;
    for (key in user) {
        if (key !== 'password') {
            newUser[key] = user[key];
        }
    }
    return newUser;
});

答案 2 :(得分:0)

您可以使用

删除每个用户的密码属性
delete connectedUser.password;