Any suggestions on how to update below JSON object as expected one in Javascript?
Have been trying to flatten JSON object based on JSON key,
- ..outer_component[x] contains section{} then moved to outer_component[x].outer_body.outer_component[x]
- ..outer_component[x] contains outer_body{} then keep on iterate till it reaches section{} and move outer_component[x].outer_body.outer_component[x]
Received JSON Object:
{
"document": {
"outer_component": [
{
"outer_body": {
"outer_component": [
{
"outer_body": {
"outer_component": [
{
"section": {
"id": [
{
"root": "INNER_11"
}
]
}
},
{
"section": {
"id": [
{
"root": "INNER_12"
}
]
}
}
]
}
},
{
"outer_body": {
"outer_component": [
{
"section": {
"id": [
{
"root": "INNER_21"
}
]
}
},
{
"section": {
"id": [
{
"root": "INNER_22"
}
]
}
}
]
}
}
]
}
},
{
"outer_body": {
"outer_component": [
{
"outer_body": {
"outer_component": [
{
"outer_body": {
"outer_component": [
{
"outer_body": {
"outer_component": [
{
"section": {
"id": [
{
"root": "INNER_31"
}
]
}
},
{
"section": {
"id": [
{
"root": "INNER_32"
}
]
}
}
]
}
},
{
"outer_body": {
"outer_component": [
{
"section": {
"id": [
{
"root": "INNER_33"
}
]
}
},
{
"section": {
"id": [
{
"root": "INNER_34"
}
]
}
}
]
}
}
]
}
}
]
}
}
]
}
}
]
}
}
Expected Output:
{
"document": {
"outer_component": [{
"section": {
"id": [{
"root": "INNER_11"
}]
}
}, {
"section": {
"id": [{
"root": "INNER_12"
}]
}
}, {
"section": {
"id": [{
"root": "INNER_21"
}]
}
}, {
"section": {
"id": [{
"root": "INNER_22"
}]
}
}, {
"section": {
"id": [{
"root": "INNER_31"
}]
}
}, {
"section": {
"id": [{
"root": "INNER_32"
}]
}
}, {
"section": {
"id": [{
"root": "INNER_33"
}]
}
}, {
"section": {
"id": [{
"root": "INNER_34"
}]
}
}]
}
}
2
Answers
I totally agree with other users comments but you can also give a try to below code,