d3.js v4: How to access parent group's datum index?

前端 未结 8 706
萌比男神i
萌比男神i 2020-11-28 10:33

The description of the selection.data function includes an example with multiple groups (link) where a two-dimensional array is turned into an HTML table.

8条回答
  •  一向
    一向 (楼主)
    2020-11-28 11:19

    Assume you want to do a nested selectiom, and your data is some array where each element in turn contains an array, let's say "values". Then you have probably some code like this:

    var aInnerSelection = oSelection.selectAll(".someClass") //
        .data(d.values) //
        ...
    

    You can replace the array with the values by a new array, where you cache the indices within the group.

    var aInnerSelection = oSelection.selectAll(".someClass") //
        .data(function (d, i) {
            var aData = d.values.map(function mapValuesToIndexedValues(elem, index) {
                    return {
                        outerIndex: i,
                        innerIndex: index,
                        datum: elem
                    };
                })
                return aData;
        }, function (d, i) {
            return d.innerIndex;
        }) //
        ...
    

    Assume your outer array looks like this: [{name "X", values: ["A", "B"]}, {name "y", values: ["C", "D"]}
    With the first approach, the nested selection brings you from here

                      d                                i
    ------------------------------------------------------------------
    root dummy X      {name "X", values: ["A", "B"]}    0
         dummy Y      {name "Y", values: ["C", "D"]}    1
    

    to here.

                 d       i
    ------------------------------------------------------------------
    root X  A    "A"     0
            B    "B"     1
         Y  C    "C"     2
            D    "D"     3
    

    With the augmented array, you end up here instead:

                 d                                              i
    ------------------------------------------------------------------
    root X  A    {datum: "A", outerIndex: 0, innerIndex: 0}     0
            B    {datum: "B", outerIndex: 0, innerIndex: 1}     1
         Y  C    {datum: "C", outerIndex: 1, innerIndex: 0}     2
            D    {datum: "D", outerIndex: 1, innerIndex: 1}     3
    

    So you have within the nested selections, in any function(d,i), all information you need.

提交回复
热议问题