Reputation: 45
How do i filter roles
in this array to return true when "Admin"
is found?
const array = [{
"country": "all",
"roles": [
"Normal",
"Admin",
]
}]
Upvotes: -1
Views: 54
Reputation: 69
1.Did u mean to return a boolean overall?
In Js es6, you could use .some()
MDN web docs
it's nice and simple :)
const array = [{
"country": "all",
"roles": [
"Normal",
"Admin",
]
}, {
"country": "test",
"roles": [
"Normal"
]
}]
const result = array.some(o => Boolean(o.roles.some(role => role === 'Admin')))
console.log(result) // return true
2.Or, did u mean that it returns a new array
in which each roles become a boolean depending on having 'Admin' or not?
If it is, .some()
works as well :)
Try below:
const array = [{
"country": "all",
"roles": [
"Normal",
"Admin",
]
}, {
"country": "test",
"roles": [
"Normal"
]
}]
const result = array.reduce((acc, curr, index) => {
const item = Object.assign({}, curr, { roles: curr.roles.some(o => o === 'Admin') })
acc.push(item)
return acc
}, [])
console.log(result) // return true
or if it filter an array, my answer is the same as Tobias' :)
Upvotes: -1
Reputation: 134
const array = [{
"country": "all",
"roles": [
"Normal",
"Admin",
]
}]
const val = array.map((a) => a.roles.includes('Admin'))
console.log(val) //return true
Upvotes: -1
Reputation: 23905
Use .filter()
and .includes()
:
const admins = array.filter((u) => u.roles.includes("Admin"))
Upvotes: 2