-1

How do i filter roles in this array to return true when "Admin" is found?

const array = [{
    "country": "all",
    "roles": [
        "Normal",
        "Admin",
    ]
}]

3 Answers 3

2

Use .filter() and .includes():

const admins = array.filter((u) => u.roles.includes("Admin"))
Sign up to request clarification or add additional context in comments.

Comments

-1

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' :)

Comments

-1
  const array = [{
   "country": "all",
   "roles": [
    "Normal",
    "Admin",
   ]
   }]

    const val = array.map((a) => a.roles.includes('Admin'))
                  
    console.log(val) //return true

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.