Nandu cg Nandu cg -4 years ago 190
Javascript Question

Javascript Nested JSON Parsing

I have a json object that object contains main nodes and nested nodes. Each node have a property "type", i want to remove the nodes object which contains the property "type = doc".Please find below example json image format. I attached 2 files one image is the input format and other one is the output format.

{
"navigations": [
{
"disp_order": "1",
"menu_id": "25266",
"nodes": [
{
"disp_order": "2",
"menu_id": "18951",
"type": "DOC"
}
],
"type": "MENU"
},
{
"disp_order": "20",
"menu_id": "25204",
"nodes": [
{
"disp_order": "1",
"menu_id": "10295",
"type": "DOC"
},
{
"disp_order": "10",
"menu_id": "25207",
"nodes": [
{
"disp_order": "999",
"menu_id": "17250",
"type": "DOC"
},

],
"type": "MENU"
},
{
"disp_order": "20",
"menu_id": "25209",
"nodes": [
{
"disp_order": "999",
"menu_id": "18881",
"type": "DOC"
},

],
"type": "MENU"
},
],
"type": "MENU"
},

]
}


Input Json Format

Output Json Format

Answer Source

https://jsfiddle.net/1hoctvdp/

function deleteNonMenu(obj) {
  if (obj.type == "DOC") {
    return true;
  }
  if (obj.nodes) {
    for (var i = 0; i < obj.nodes.length; i++) {
      var res = deleteNonMenu(obj.nodes[i]);
      if (res == true) {
        delete obj.nodes[i];
      }
    }
  }
  return false;
}

for (var i = 0; i < json.navigations.length; i++) {
  var result = deleteNonMenu(json.navigations[i]);
  if (result == true) {
    delete json.navigations[i];
  }
}
console.log(json);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download