Search code examples
jsond3.jstreemap

How to loop through a d3 json treemap to get section nodes


How do i loop through a treemap json object that might look like this: and only return Section nodes as appose to node under each section node? So, one might have a structure that looks kind of like this:

{
  name: "products"
  children:[
    {
      name: "Wood", 
      children: [
        { name: "rose wood" },
        { name: "maple" }
      ]
    },
    {
      name: "Metals", 
      children: [
        { name: "Iron" },
        { name: "copper" }
      ]
    }
  ]
}
//end

What is want is to return only "Wood", "Metals" etc. Due to the redundant nature of the data, a straight forward loop does not cut it. Any ideas? Thanks.


Solution

  • Here is my code with the approach that solved my JSON parsing problem.

    .on("mouseover",function (d) {
         $("#treemapPopup").show().html(
                  "<h4>"+d.parent.name +"</h4>"+
                      "<p><strong>Good:</strong> "+d.name+"<br />"+
                      //Math.round(percent* 10)/10+"% <br />"+
                      "<strong>Countries:</strong></p>"+
                        courtryList
              );
    }) ...etc
    

    The d.parent.name ends up being Wood, Metals, etc as I traverse the children array of objects. And, of course, d.name is the product under Wood or Metal. Hope that helps anyone else who may have been stuck on this.