Kim
Kim

Reputation: 11

GROOVY transform single array into deep nested array

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
    }]
}]

Upvotes: 0

Views: 186

Answers (1)

cfrick
cfrick

Reputation: 37033

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]]]]

Upvotes: 1

Related Questions