1

My sample JSON , I would like to rebuild below json by removing "Child:" Object

{  
   "Child":{  
      "DeviceList":[  
         {  
            "Child":null,
            "DeviceId":"7405618",
            "Signal":"-90"
         },
         {  
            "Child":{  
               "DeviceList":[  
                  {  
                     "Child":{  
                        "DeviceList":[  
                           {  
                              "Child":null,
                              "DeviceId":"3276847",
                              "Signal":"-86"
                           }
                        ]
                     },
                     "DeviceId":"2293808",
                     "Signal":""
                  }
               ]
            },
            "DeviceId":"4915247",
            "Signal":"-90"
         }
      ]
   }
}

New structure should look like this

{  
   "DeviceList":[  
      {  
         "DeviceList":null,
         "DeviceId":"7405618",
         "Signal":"-90"
      },
      {  
         "DeviceList":[  
            {  
               "DeviceList":[  
                  {  
                     "DeviceList":null,
                     "DeviceId":"3276847",
                     "Signal":"-86"
                  }
               ],
               "DeviceId":"2293808",
               "Signal":""
            }
         ],
         "DeviceId":"4915247",
         "Signal":"-90"
      }
   ],
   "DeviceId":"4915247",
   "Signal":"-90"
}

I am looking for a nested recursive solution for a dynamic json tree structure where my JSON content will look like the sample provided.

1
  • you want to 'skip' Child key? Commented Feb 11, 2017 at 18:09

1 Answer 1

1

You could use an iterative and recursive approach for moving DeviceList to the place of Child.

var data = { Child: { DeviceList: [{ Child: null, DeviceId: "7405618", Signal: "-90" }, { Child: { DeviceList: [{ Child: { DeviceList: [{ Child: null, DeviceId: "3276847", Signal: "-86" }] }, DeviceId: "2293808", Signal: "" }] }, DeviceId: "4915247", Signal: "-90" }] } };

[data].forEach(function iter(a) {
    if ('Child' in a) {
        a.DeviceList = a.Child && a.Child.DeviceList;
        delete a.Child;
        if (Array.isArray(a.DeviceList)) {
            a.DeviceList.forEach(iter);
        }
    }
});

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sign up to request clarification or add additional context in comments.

1 Comment

you need to handle the case where "Child" is null. it should still be replaced with "DeviceList" = null.

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.