简体   繁体   中英

Access different levels of nested lists in d3

Suppose I have a list with the following format:

dataset = [["10", "asdf"], ["20", "jkl"], ["30", "bla"]]

I want to append text for each individual character in the second element of each nested list. I also want the x position of each letter to be determined by the first element of the list. So, for example, the x position of a should be 10 , for s - 11 , d - 12 ... for j - 20 , for k - 21 , and so forth.

In the code I have so far, I only show the first letter, because I'm not iterating through the correct portion of the list:

chartBody.selectAll("exampletext")
                       .data(dataset)
                       .enter()
                       .append("text")
                       .attr("class", "exampletext")
                       .text(function(d) {
                            for (var i=0; i <= d[1].length; i++)
                                {
                                    return d[1][i];
                                }
                       })
                       .attr("x", function(d) {
                            for (var i=0; i <= d[1].length; i++)
                                {
                                    return xScale(+d[0]) + i; 
                                }
                       })
                       .attr("y", h/2);

I don't know why you need this (it's really hard to read that output) but here it is: http://jsfiddle.net/uNQA9/ .

The important change was to build the list of letters and positions prior to feeding to d3:

var dataset, h, i, letter, pair, r, viewport, xScale, _i, _j, _len, _len1, _ref;

dataset = [["10", "asdf"], ["20", "jkl"], ["30", "bla"]];

r = [];    
i = 0;

/*loop each pair, push into a new array */


for (_i = 0, _len = dataset.length; _i < _len; _i++) {
  pair = dataset[_i];
  i = 0;
  _ref = pair[1];
  for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) {
    letter = _ref[_j];
    r.push([+pair[0] + i, letter]);
    i++;
  }
}

That JS is ugly (but uber compliant) because I got it from this bit of (nicely readable) coffeescript:

dataset = [["10", "asdf"], ["20", "jkl"], ["30", "bla"]]
r = []
i = 0 
#loop each pair, push into a new array
for pair in dataset
  i = 0
  for letter in pair[1]
    r.push([+(pair[0]) + i, letter]) 
    i++ 

I made a slightly more readable version here: http://jsfiddle.net/UtUeP/ . If you want to pump up the difference between the letters, check out the d3 colors functions like: d3.scale.category10() : https://github.com/mbostock/d3/wiki/Ordinal-Scales

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM