This is the input object :
{
"items": [{}],
"modular_content": {
"first_child_b": {
"elements": {
"subpages": {
"type": "modular_content",
"name": "Children Pages",
"value": ["second_child_b"]
}
}
},
"second_child_b": {
"elements": {
"subpages": {
"type": "modular_content",
"name": "Children Pages",
"value": []
}
}
},
"top_level_b": {
"elements": {
"subpages": {
"type": "modular_content",
"name": "Children Pages",
"value": ["first_child_b"]
}
}
}
}
}
This is my expected response:
{
items: [ {} ],
modular_content: {
first_child_b: {
elements: {
subpages: {
type: 'modular_content',
name: 'Children Pages',
value: [ 'second_child_b' ],
data: [
{
elements: {
subpages: {
type: 'modular_content',
name: 'Children Pages',
value: [],
data: []
}
}
}
]
}
}
},
second_child_b: {
elements: {
subpages: {
type: 'modular_content',
name: 'Children Pages',
value: [],
data: []
}
}
},
top_level_b: {
elements: {
subpages: {
type: 'modular_content',
name: 'Children Pages',
value: [ 'first_child_b' ],
data: [
{
elements: {
subpages: {
type: 'modular_content',
name: 'Children Pages',
value: [ 'second_child_b' ],
data: [
{
elements: {
subpages: {
type: 'modular_content',
name: 'Children Pages',
value: [],
data: []
}
}
}
]
}
}
}
]
}
}
}
}
}
Basically, if the subpage value array has some value and it is present in the modular_content object, I want to append it inside the parent object.
This is my jsonata expression
(
$hasProperty := function ($obj, $field){
$lookup($obj, $field)? true: false
};
$nestSubpages := function ($field) {
$hasProperty(modular_content, $field)?
(
$subPageValue := $lookup(modular_content, $field).elements.subpages.value;
$nestedSubpages := $map($subPageValue, function($subPage){$nestSubpages($subPage)});
$ ~> | $lookup(modular_content, $field).elements.subpages| { "data" : $nestedSubpages } |
)
:
{}
};
$each(modular_content, function ($v, $k){
$nestSubpages($k)
})
)
https://try.jsonata.org/NtyRb5A9z In this expression, the whole input object is embedded instead of only the child object. Also, this returns an array of objects (1 obj for each key).