1

I'm making a treemap in d3, which requires data as a series of nested objects, like so:

{
    name: "flare",
    children: [
        {
            name: "analytics",
            children: [
                {
                    name: "cluster",
                    children: [
                        {
                            name: "AgglomerativeCluster",
                            size: 3938
                        },
                        {
                            name: "CommunityStructure",
                            size: 3812
                        }
                    ]
                }
            ]
        }
    ]
}

The natural way to gather this data behind the scenes is as a dictionary (in Python terminology), like so:

{
    "flare": {
         "analytics": {
              "cluster": [
                   {
                       name: "AgglomerativeCluster",
                       size: 3938
                   },
 //etc etc

What's the most natural way to get from the latter to the former without writing nested loops by hand?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Chris Wilson
  • 6,599
  • 8
  • 35
  • 71

1 Answers1

0

EDIT: I just realized my answer does the operation in the wrong way (from the first version to the second). However you can use the same principle for the other way.

You might also want to have a look at d3.nest(), as described here: D3 JSON data conversion


I would create a recursive function to achieve this goal. I had to use jQuery to map each element of the children array its updated version:

function reduce(dataset){ 
    if('children' in dataset) {
        var tmp = {}
        tmp[dataset.name] = $.map(dataset.children, function(d){return reduce(d)})
        return tmp
    } else {
        return dataset
    }
}

Which gives, when applied to your example dataset:

{
    "flare": [{
        "analytics": [{
            "cluster": [{
                "name": "AgglomerativeCluster",
                "size": 3938
            }, {
                "name": "CommunityStructure",
                "size": 3812
            }]
        }]
    }]
}

jsFiddle: http://jsfiddle.net/chrisJamesC/kKDm3/

Community
  • 1
  • 1
Christopher Chiche
  • 15,075
  • 9
  • 59
  • 98