Home > Back-end >  How can I parse these list elements?
How can I parse these list elements?

Time:09-23

I'd like to parse the following look up table as follows:

I want to check the branch name and fetch the corresponding name value, but i want to do fetch first name of each branch, like:

[branch: "test"] => name "a" then [branch: "test-1"] => name "d"

and so on.

LUT = [
    [branch: "test", name: 'a', image_name: 'abc'],
    [branch: "test", name: 'b', image_name: 'abc'],
    [branch: "test", name: 'c', image_name: 'abc'],
    [branch: "test-1", name: 'd', image_name: 'abc'],
    [branch: "test-1", name: 'e', image_name: 'abc'],
    [branch: "test-2", name: 'f', image_name: 'abc'],
    [branch: "test-2", name: 'g', image_name: 'abc'],
    [branch: "test-2", name: 'h', image_name: 'abc'],
    [branch: "test-3", name: 'i', image_name: 'abc'],
    [branch: "test-3", name: 'j', image_name: 'abc'],
    [branch: "test-4", name: 'k', image_name: 'abc'],
    [branch: "test-5", name: 'l', image_name: 'abc'],
]

for example the result may look like:

result = {
 "test": [{ "name":"a" }],
 "test-1": [{ "name":"d" }],
 "test-2": [{ "name":"f" }],
 "test-3": [{ "name":"i" }], 
"test-4": [{ "name":"k" }], 
"test-5": [{ "name":"l" }], 
} 

Also, I might like to add additional values to the keys for example in test-1:

"test-1": [{ "name": "a", "new_name": "new" }]

CodePudding user response:

Not positive how to format the result like you want it but finding the first instance of each branch is fairly easy.

result = [:]
for (map in LUT)
{
    if (!result.containsKey(map['branch']))
    {
        println map['name'] // prints the unique name
        result.put(map['branch'], map['name'])
    }
}

CodePudding user response:

I'm not sure about your curly brackets, but this creates a map:

def original = [
    [branch: "test", name: 'a', image_name: 'abc'],
    [branch: "test", name: 'b', image_name: 'abc'],
    [branch: "test", name: 'c', image_name: 'abc'],
    [branch: "test-1", name: 'd', image_name: 'abc'],
    [branch: "test-1", name: 'e', image_name: 'abc'],
    [branch: "test-2", name: 'f', image_name: 'abc'],
    [branch: "test-2", name: 'g', image_name: 'abc'],
    [branch: "test-2", name: 'h', image_name: 'abc'],
    [branch: "test-3", name: 'i', image_name: 'abc'],
    [branch: "test-3", name: 'j', image_name: 'abc'],
    [branch: "test-4", name: 'k', image_name: 'abc'],
    [branch: "test-5", name: 'l', image_name: 'abc'],
]

println original
    .groupBy { branch -> branch.branch }
    .collectEntries { key,value -> [(key) : [name : value.get(0).name]] }
  • Related