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/