0

I have an array as the source. I want to transform source into result by using Groovy. I don't see any similar question. That's why I post here.

I tried to get the first member in the family and put all other members into a subList with this code but it failed

source.each{ family -> family.each{ 
        member -> member.get(0).collate(1,family.size()-1)
    }
}

source:

[
  [{
        "id": "0001",
        "role": "parent",
        "age": 30
    },
    {
        "id": "0002",
        "role": "child",
        "age": 1
    },
    {
        "id": "0003",
        "role": "child",
        "age": 3
    }
],
[{
        "id": "0004",
        "role": "parent",
        "age": 31
    },
    {
        "id": "0005",
        "role": "child",
        "age": 5
    }
  ]
]

result:

[{
    "id": "0001",
    "role": "parent",
    "age": 30,
    "children": [{
            "id": "0002",
            "role": "child",
            "age": 1
        },
        {
            "id": "0003",
            "role": "child",
            "age": 3
        }
    ]
},
{
    "id": "0004",
    "role": "parent",
    "age": 31,
    "children": [{
        "id": "0005",
        "role": "child",
        "age": 5
    }]
}]

1 Answer 1

1

You can shape the data by adding the "parent" map with a new map only containing the children (+ in groovy does that merge). E.g.:

def data = new groovy.json.JsonSlurper().parseText('[[{ "id": "0001", "role": "parent", "age": 30 }, { "id": "0002", "role": "child", "age": 1 }, { "id": "0003", "role": "child", "age": 3 } ], [{ "id": "0004", "role": "parent", "age": 31 }, { "id": "0005", "role": "child", "age": 5 }]]')

println(data.collect{ groups ->
    // XXX
    groups.find{ it.role=="parent" } + [children: groups.findAll{it.role=="child"}] 
})
// => [[id:0001, role:parent, age:30, children:[[id:0002, role:child, age:1], [id:0003, role:child, age:3]]], [id:0004, role:parent, age:31, children:[[id:0005, role:child, age:5]]]]
Sign up to request clarification or add additional context in comments.

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.