dbrin
dbrin

Reputation: 15673

Groovy: Maps deep nesting

I got a map matrix that looks like this:

def matrix = [
    field1:[role1:[state1:["f1r1s1",true],
                   state2:["f1r1s2",false]],
            role2:[state1:["f1r2s1",true],
                   state2:["f1r2s2",false]]
           ],
    field2:[role1:[state1:["f2r1s1",true],
                   state2:["f2r1s2",false]],
            role2:[state1:["f2r2s1",true],
                   state2:["f1r2s2",false]]
           ]
]

I am trying to get all fields where role is "role1" and state is "state1". Easy? Help pls.

Upvotes: 2

Views: 5485

Answers (2)

tim_yates
tim_yates

Reputation: 171054

You can do:

def map = matrix.inject([:]) { map, elem -> map << [ (elem.key): elem.value[ 'role1' ][ 'state1' ] ] }

to get your required result:

[field1:[f1r1s1, true], field2:[f2r1s1, true]]

Upvotes: 5

winstaan74
winstaan74

Reputation: 1131

matrix.values().role1.state1

works for this case, as you've only got a single level of unknown to search through.

Upvotes: 7

Related Questions