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

标签 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,只有管理员可以访问此路由并且密码已加密,但我想将它们从请求中排除。那么如何过滤排除密码属性的对象呢?

最佳答案

filter() 用于过滤条目;即,如果您为某个条目返回 true,则它会包含在结果中,否则会被丢弃。因此,您不能使用 filter() 来转换输入。相反,您应该将过滤后的结果映射到没有密码的对象:

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

附言。我对您的过滤器功能做了一个小改动。

关于javascript - 从数组返回对象时排除属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25953763/

相关文章:

javascript - 根据原始值更改输入值

javascript - Firebase orderByChild 意外结果

javascript - 未捕获的类型错误 : Illegal invocation when looping through object

python - 尝试使用类函数在第二个类中调用该类中的另一个函数时获取 "AttributeError"

javascript - jQuery 选择器到 JSON 对象表示

javascript - 在 jQuery 中更改背景颜色

javascript - 错误: 7 PERMISSION_DENIED: Your application has authenticated using end user credentials from the Google Cloud SDK

javascript - 缩小外部网址和多个样式表

ruby-on-rails - 如何一次为 Ruby 中的对象分配多个属性

JavaScript 对象方法返回 null 属性