Reputation: 5619
I fetch a list of users from aws cognitio, that works perfectly.
Now I want to iterate over this array and remove those which don't match to a Client ID, that does not work properly.
what is my failure in this case?
My code looks like this:
this.awsSDKAuth().listUsers(params, (err, data) => {
if (err) console.log(err, err.stack); // an error occurred
else {
let userArray = data.Users.slice(0);
console.log(userArray);
userArray.forEach((user,index) => {
user.Attributes.forEach(attr => {
if(attr.Name === "custom:client" && attr.Value !== clientId){
userArray.splice(index,1);
console.log(userArray);
}
}
)});
console.log(userArray);
this.setState({
users: userArray
})
}
});
Thanks
In this case I got two useres one with clientID = 36 and one with clientID = 35.
only the one with 36 should be displayed
Question: Should I do this recoursive? Breac the foreach when one is found and start again? maybe of wrong indexing?
Upvotes: 1
Views: 89
Reputation: 12029
This might do it for you. You can filter the users based on the criteria that the user returns an attribute that has the correct name and value.
this.awsSDKAuth().listUsers(params, (err, data) => {
if (err) {
console.log(err, err.stack); // an error occurred
} else {
this.setState({
users: data.Users.filter(user => user.Attributes.some(attr => attr.Name === "custom:client" && attr.Value === clientID)),
});
}
});
Upvotes: 0
Reputation: 45121
what is my failure in this case?
You are mutating array while iterating over it. Use filter
instead.
this.awsSDKAuth().listUsers(params, (err, data) => {
if (err) console.log(err, err.stack); // an error occurred
else {
let userArray = data.Users.slice(0)
.filter(user => user.Attributes.some(attr => attr.Name === "custom:client" && attr.Value === clientId));
this.setState({
users: userArray
})
}
});
const userData = [{
Attributes: [{
name: 'custom:client',
value: '36'
},
{
name: 'FirstName',
value: 'Keep'
}
]
},
{
Attributes: [{
name: 'custom:client',
value: '35'
},
{
name: 'FirstName',
value: 'Omit'
}
]
},
{
Attributes: [{
name: 'custom:client',
value: '36'
},
{
name: 'FirstName',
value: 'Keep'
}
]
},
{
Attributes: [{
name: 'custom:client',
value: '37'
},
{
name: 'FirstName',
value: 'Omit'
}
]
}
]
console.log(
userData.filter(user => user.Attributes.some(attr => (attr.name === 'custom:client' && attr.value === '36')))
)
Upvotes: 3