D3.js: Get an array of the data attached to a selection?

后端 未结 4 503
耶瑟儿~
耶瑟儿~ 2021-02-01 17:39

I\'d like to get an array of all the data attached to a selection in D3.

I\'m working with the example from the General Update pattern, and trying this:

         


        
4条回答
  •  时光取名叫无心
    2021-02-01 18:18

    This is an old question but I was also wondering about it. The state passed in through selection.data is not lost but it is dispersed across the update and enter groups. It can be retrieved, in tact, reasonably reliably with this function...

    function getData2(/*this is update*/) {
        if (this.enter /*quick duck type test...*/) {
            var enter = this.enter(), retVal = []
    
            for (var i = 0; i < this.length; i++) {
    
                retVal.push([])
    
                for (var j = 0; j < enter.length; j++) {
                    retVal[i].push(enter[i][j] || enter[i].update[j])
                    retVal[i][j] = retVal[i][j] && retVal[i][j].__data__
                    if (!retVal[i][j]) {
                        retVal[i].pop()
                    } 
                }
    
            }
            return (this.length > 1 ? retVal : retVal[0])
        }
    }
    

    usage...

    console.log(getData2.call(update))
    

    OR...

    d3.selection.prototype.data2 = getData2
    // ...
    console.log(update.data2())
    

    where update is the update collection returned by selection.data(array)

提交回复
热议问题