Reputation: 13412
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
}
});
The above returns all the users connected, this is to build an api for my app, only admin's can access this route and the passwords are encrypted but I would like to exclude them from the request. So how do I filter the object with an exclusion to password attr?
Upvotes: 1
Views: 1130
Reputation: 193261
You should map filtered array removing password from each element. You can do it by creating a new use object without password property:
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;
});
Upvotes: 1
Reputation: 1379
filter()
is for filtering entries; ie, if you return true for an entry it is included in the results, otherwise it's dropped. As such, you can't use filter()
to transform the input. Instead, you should map
the filtered results to objects without the passpword:
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. I made a tiny change to your filter function.
Upvotes: 1
Reputation: 12300
You can delete the password attribute of each user using
delete connectedUser.password;
Upvotes: 0