Create Legend for Hierarchy Data (ICD-10 Candidate)

http://stackoverflow.com/questions/21502187/how-to-create-legend-for-d3-sequence-sunburst

by Nivaldo

HTML

<!--
- if doing this after the data has become a D3 selection, can then use .each to create an array with the node name, node depth in the tree, etc., thus allowing for a more fine-grained customization of the legend
-->

JavaScript

var root = {
    "name": "Chapter-5 Mental, Behavioral and Neurodevelopmental disorders",
    "firstnode": "true",
    "key": "Mental, Behavioral and Neurodevelopmental disorders",
    "group": 0,
    "children": [{
        "name": "F01-F09 Mental disorders due to known physiological conditions",
        "key": "Mental disorders due to known physiological conditions",
        "group": 1,
        "children": [{
            "name": "F01 Vascular dementia",
            "group": 1,
            "children": [{
                "name": "F01.5 Vascular dementia",
                "group": 1,
                "children": [{
                    "name": "F01.50 Vascular dementia without behavioral disturbance",
                    "group": 1
                }, {
                    "name": "F01.51 Vascular dementia with behavioral disturbance",
                    "group": 1
                }]
            }]
        }, {
            "name": "F02 Dementia in other diseases classified elsewhere",
            "group": 1,
            "children": [{
                "name": "F02.8 Dementia in other diseases classified elsewhere",
                "group": 1,
                "children": [{
                    "name": "F02.80 Dementia in other diseases classified elsewhere without behavioral disturbance",
                    "group": 1
                }, {
                    "name": "F02.81 Dementia in other diseases classified elsewhere with behavioral disturbance",
                    "group": 1
                }]
            }]
        }, {
            "name": "F03 Unspecified dementia",
            "group": 1,
            "children": [{
                "name": "F03.9 Unspecified dementia",
                "group": 1,
                "children": [{
                    "name": "F03.90 Unspecified dementia without behavioral disturbance",
                    "group": 1
                }, {
                    "name": "F03.91 Unspecified dementia with behavioral disturbance",
        ...