How do i filter roles in this array to return true when "Admin" is found?
const array = [{
"country": "all",
"roles": [
"Normal",
"Admin",
]
}]
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' :)