javascript - Handling Different Child Object Names Recursively -


i'm working nested json feed d3.js

my code works fine when child object named children, want able display nodes few of other objects too, not ones named children.

for example, if within children object, have object named options. want display nodes object well.

{     "item": [{         "children": [{             "name": "banana",             "definition": "this fruit",             "group": "n",             "options": [                 {                         "color": "red",                         "shape": "square"                 }             ],             "countries": [                 {                         "color": "america",                         "shape": "africa"                 }             ]         },         {             "name": "apple",             "definition": "this fruit",             "group": "n",             "options": [                 {                         "color": "red",                         "shape": "square"                 }             ]         }]     }] } 

here recursive function have within flatten function:

// returns list of nodes under root. function flatten(root) {     var nodes = [], = 0;      function recurse(node) {         if (node.children) {             node.size = node.children.reduce(function(p, v) {                  return p + recurse(v);             }, 0);         }         if (!node.id) node.id = ++i;         nodes.push(node);         return node.size;     }      root.size = recurse(root);     return nodes; } 

does have idea how 1 go please?

this question doesn't have jquery or d3; it's plain javascript , json.

if want code work other array in json object, it's matter of replacing if statement check d["children"] go through attributes of json object , recurse on array instead. this:

function flatten(root) {     var nodes = [], = 0;      function recurse(node) {         (var x in node) {             if (array.isarray(node[x])) {                 node.size = node[x].reduce(function(p, v) {                      return p + recurse(v);                 }, 0);             }         }          if (!node.id) node.id = ++i;         nodes.push(node);         return node.size;     }      root.size = recurse(root);     return nodes; } 

Comments

Popular posts from this blog

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

c++ - OpenMP unpredictable overhead -

javascript - Wordpress slider, not displayed 100% width -