Sahand Javid
Sahand Javid

Reputation: 13

How can I filter javascript objects with an expression that has array in it with jmesPath?

I have an array of users and each user has couple of roles. The example of the array is shown below.

[
    {
        id: 1,
        username: 'john',
        roles: [
            {id: 500, name: 'Admin'},
            {id: 501, name: 'Owner'}
        ]
    },
    {
        id: 2,
        username: 'joe',
        roles: [
            {id: 500, name: 'Admin'},
        ]
    },
    {
        id: 3,
        username: 'june',
        roles: [
            {id: 502, name: 'User'},
        ]
    }
]

I'm trying to get all the users who have an Admin role by using jmesPath. I've tried [?roles[].name=='Admin'] but this is giving a null value. Is is possible to do this with jmesPath, and if yes can you give me an expression for this example?

Upvotes: 1

Views: 1871

Answers (2)

diedu
diedu

Reputation: 20775

I played a little with this example and your data

http://jmespath.org/examples.html#filtering-and-selecting-nested-data

I made it work with this expression

[?roles[?name=='Admin']]

Upvotes: 4

José Quinto Zamora
José Quinto Zamora

Reputation: 2118

You can get the same result with plain JavaScript using:

Assuming your array is stored on var users = [...].

users.filter((i)=> i.roles.some((s) => s.name === "Admin"))

You can see this sample with jsBin

Upvotes: -1

Related Questions