Skip to content Skip to sidebar Skip to footer

Flattening A Nested Object

I have to convert JSON to the format below, I'm having a problem converting it back. Here is the current format [{ 'id': '5', 'parentid': '0', 'text': 'Device Guides',

Solution 1:

A first solution, granted you don't want the resulting array to be sorted based on the id:

function visitor(graph) {
  var i, l,
  nodes=[],
  visited=[];

  function clone(n) {
     // improve the function yourself I'm lazy
     var i,l,
         props=["id","parentid","index","text"],
         result={};
     for (i = 0, l = props.length; i < l; i++) { 
        if (n[props[i]]) {
          result[props[i]]= n[props[i]];
        }
     }
     return result;
  }

  function helper (node) {
    var i, limit;
    if (visited.indexOf(node.id) == -1) {
      visited.push(node.id);
      nodes.push(clone(node));
      if( node.children) {
        for (i = 0, limit = node.children.length; i < limit; i++) {
          helper(node.children[i]);
        }
      }
    }
  }

  for (i = 0, l = graph.length; i < l; i++) {
    helper(graph[i]);
  }

  return nodes;
}

var graph =     [{
    "id": "5",
    "parentid": "0",
    "text": "Device Guides",
    "index": 0,
    "children": [{
        "id": "10",
        "text": "Grandstream GXP-21XX",
        "index": 0
    }, {
        "id": "11",
        "text": "Polycom Soundstation/Soundpoint",
        "index": 1
    }, {
        "id": "23",
        "text": "New Polycom",
        "index": 2
    }]
}, {
    "id": "6",
    "parentid": "0",
    "text": "Pre-Sales Evaluation",
    "index": 1,
    "children": []
}, {
    "id": "7",
    "parentid": "0",
    "text": "Router Setup Guides",
    "index": 2,
    "children": [{
        "id": "9",
        "text": "Sonicwall",
        "index": 0
    }, {
        "id": "12",
        "text": "Cisco",
        "index": 1
    }]
}, {
    "id": "9",
    "parentid": "7",
    "text": "Sonicwall",
    "index": 3,
    "children": []
}, {
    "id": "10",
    "parentid": "5",
    "text": "Grandstream GXP-21XX",
    "index": 4,
    "children": []
}, {
    "id": "11",
    "parentid": "5",
    "text": "Polycom Soundstation/Soundpoint",
    "index": 5,
    "children": []
}, {
    "id": "12",
    "parentid": "7",
    "text": "Cisco",
    "index": 6,
    "children": []
}];

nodes = visitor(graph);

And yes, I know, the helper function relay on side effects but I've scoped them into the visitor function to reduce harm and there is room for improvements (at least sorting the resulting array based on the id) but I will leave them to you


Post a Comment for "Flattening A Nested Object"