简体   繁体   中英

D3 trying to access vis element in json object

I'm trying to access the vis element in the json object below using D3 (see screenshot), but am unable to do so. I can access the key and value elements without any problems using code similar to the following:

console.log(d.key);

but this does not work (I get an undefined error):

console.log(d.vis);

Any ideas what I am doing wrong? Thank you!

json obj

Here are some code snippets:

var nested = d3.nest().key(function(d) { return d._id.stream; })
  .entries(data.result);

var stream = main.selectAll(".stream")
  .data(nested)
  .enter().append("g")
  .attr("class", "stream");    

  stream.append("rect")
  .attr("height",10)
  .attr("width", 25)
  .attr("x",width-215)
  .attr("y", function(d,i) { return height-400 + (i*40); })
  .attr("stroke", function(d) { return color(d.key);})
  .attr("fill",function(d) {
      if(d.vis=="1") {
        return color(d.key);
      }
      else {
        return "white";
      }
   })
   .on("click", function(d) {
     console.log(d);
     console.log(d.vis);  // undefined
     if(d.vis=="1") {
        d.vis="0";
      }
      else{
        d.vis="1";
      }
   });

It looks like the following is happening. The click handler function is executed. Inside, you're logging d.vis , which is undefined. The code immediately after that checks whether d.vis has a particular value, else sets it to "1". This "else" includes the undefined case.

So after the handler has been executed, d.vis is set for all d . The debugger you're using shows the value of the variable, which was modified after the console.log() statement . That is, at the time when you printed d , d.vis was indeed undefined. But you're setting it immediately afterwards, and that's what you get in the console.

The log doesn't take a snapshot of the state of the variable when it's printed, but shows you the current version which, in this case, has d.vis set.

pay attention to the data structure: see the fetchData.js, other than priceList and name, there should be vis element for determining whether to show the curve or not.

//The main data array of the graph
//format:
//data2 (List of fundObj)
//   fundObj (Name, priceList)
//      Name
//      vis
//      priceList (List of priceItem)
//         priceItem (date, price)

so, be clear about what is "d" in the code, it all depends on the data you passed to the call:

var fund = focus.selectAll(".fund")
        .data(data2)
        .enter().append("g")
        .attr("class", "fund");

Here data2 is the raw data, you may use other structure, but need to modify some of the code in places of "d".....

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