I have an array that contains some objects:
const array = [
{
id: 1,
username: "username1",
roles: [
{
id: 1,
name: "ROLE_USER"
},
{
id: 8,
name: "ROLE_ADMIN"
}
]
},
{
id: 2,
username: "username2",
roles: [
{
id: 1,
name: "ROLE_USER"
},
{
id: 10,
name: "ROLE_TESTER"
}
]
},
{
id: 3,
username: "username3",
roles: [
{
id: 1,
name: "ROLE_USER"
},
{
id: 8,
name: "ROLE_ADMIN"
}
]
}
]
Now, how do I filter these objects by role? I wanted to get users with "ROLE_ADMIN" only. I tried doing something like:
const admins = array.filter(user => user.roles.filter(role => role.name === "ROLE_ADMIN"));
and
const admins = array.filter(user => user.roles.map(role => role.name === "ROLE_ADMIN"));
and
const admins = array.map(user => user.roles.filter(role => role.name === "ROLE_ADMIN"));
but none of these worked. Can someone help me?
Try to combine filter with some
According to MDN docs:
The
some()method tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value.
Below snippet could help you
const data = [
{
id: 1,
username: 'username1',
roles: [
{
id: 1,
name: 'ROLE_USER'
},
{
id: 8,
name: 'ROLE_ADMIN'
}
]
},
{
id: 2,
username: 'username2',
roles: [
{
id: 1,
name: 'ROLE_USER'
},
{
id: 10,
name: 'ROLE_TESTER'
}
]
},
{
id: 3,
username: 'username3',
roles: [
{
id: 1,
name: 'ROLE_USER'
},
{
id: 8,
name: 'ROLE_ADMIN'
}
]
}
]
const res = data.filter(user =>
user.roles.some(role => role.name === 'ROLE_ADMIN')
)
console.log(res)
An empty array or object will still be truthy in JavaScript. Add .length > 0 for roles filter (your first option) as below
const admins = array.filter(user => user.roles.filter(role => role.name === "ROLE_ADMIN").length > 0);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With