secondman
secondman

Reputation: 3287

Loop Object Values and Check if they Exist in a Different Object

I need to pass a string with or without pipe separated role names, and see if any of those names exist within an existing javascript array.

Using .includes works great if it's a single name, but when I have a piped set of names my function won't return true even if any of the names exist in the array.

is(roleName) {
    let roles = roleName.split('|')

    return roles.forEach(role => {
        return this.$page.auth.user.roles.includes(role) 
    })
}

This is a mixin method for Vue btw.

Thanks

Upvotes: 0

Views: 24

Answers (1)

Sphinx
Sphinx

Reputation: 10729

Uses Array.every if you'd like to check if all roles exist in users.roles.

is(roleName) {
    let roles = roleName.split('|')

    return roles.every(role => {
        return this.$page.auth.user.roles.includes(role) 
    })
}

Uses Array.some if you'd like to check if any one of the roles exist in users.roles.

is(roleName) {
    let roles = roleName.split('|')

    return roles.some(role => {
        return this.$page.auth.user.roles.includes(role) 
    })
}

Upvotes: 2

Related Questions