d3.nest() key and values conversion to name and children

后端 未结 4 1240
梦谈多话
梦谈多话 2020-12-05 08:31

I am working on creating a Treemap from a csv file. The data in the csv file is hierarchical, as a result I used d3.nest().

However, the resulting JSON

4条回答
  •  一整个雨季
    2020-12-05 09:10

    I completely agree with @Anderson that the easiest approach to this issue is to use the treemap children(function) and .value(function) methods to specify the names of the properties within the nested dataset.

    However, a duplicate question has recently been posted in which the questioner specifically asks for help using an Array.map approach. So here it is:

    The array map(function) method creates a new array where each element in the array is the result of running the specified function on each element of the original array. Specifically, the function is run with up to three arguments: the element from the original array, the index of that element, and the original array as a whole. For the purposes of manipulating the property names, we only need the first argument.

    The nested data in the original post has three levels, equivalent to the three key functions. Therefore, we're going to need a three-level mapping function:

    var treeData = {
        "key": "World",
        "values": d3.nest()
            .key(function(d) {
                return d.Major_Region;
            })
            .key(function(d) {
                return d.Region;
            })
            .key(function(d) {
                return d.Country;
            })
            .entries(pop)
    };
    
    var treeData2 = {
        "name": "World",
        "children": treeData.values.map(function(major) {
    
            return {
                "name": major.key,
                "children": major.values.map(function(region) {
    
                    return {
                        "name": region.key,
                        "children": region.values.map(function(country) {
    
                            return {
                                "name": country.key,
                                "children": country.values
                            };
    
                        }) //end of map(function(country){
                    };
    
                }) //end of map(function(region){
            };
    
        }) //end of map(function(major){
    }; //end of var declaration
    

    You could also probably implement this with a recursive function, which would be especially useful if you had many more levels of nesting.

提交回复
热议问题