Handling child names recursively
I am working with nested JSON feed with D3.js
My code works fine when the child object has a name children
, but I want to be able to display nodes for several other objects, not just the ones that are named children
.
For example, if inside an object children
I have another object named options
. I also want to display nodes for this object.
{
"item": [{
"children": [{
"name": "banana",
"definition": "this is a fruit",
"group": "n",
"options": [
{
"color": "red",
"shape": "square"
}
],
"countries": [
{
"color": "america",
"shape": "africa"
}
]
},
{
"name": "apple",
"definition": "this is a fruit",
"group": "n",
"options": [
{
"color": "red",
"shape": "square"
}
]
}]
}]
}
Here is the recursive function I have in my anti-aliasing function:
// Returns a list of all nodes under the root.
function flatten(root) {
var nodes = [], i = 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 anyone know how this can be done?
source to share
This question really has nothing to do with jQuery or D3; it's just JavaScript and JSON.
If you just want your code to work with any other array in your JSON object, it's just a matter of replacing your if statement where you check d["children"]
to go through all the attributes of the JSON object and overwrite whatever is the array. Something like that:
function flatten(root) {
var nodes = [], i = 0;
function recurse(node) {
for (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;
}
source to share