Discovering the key for an array or accessing a specific property value

Is it feasible to use D3 to locate the key associated with a specific value?

For instance, in the provided array below, how can one extract "Red Delicious" when referencing the value d.y:

[
  { year: "2006", redDelicious: "10", mcintosh: "15", oranges: "9", pears: "6" },
  { year: "2007", redDelicious: "12", mcintosh: "18", oranges: "9", pears: "4" },
  { year: "2008", redDelicious: "05", mcintosh: "20", oranges: "8", pears: "2" },
  { year: "2009", redDelicious: "01", mcintosh: "15", oranges: "5", pears: "4" },
  { year: "2010", redDelicious: "02", mcintosh: "10", oranges: "4", pears: "2" },
  { year: "2011", redDelicious: "03", mcintosh: "12", oranges: "6", pears: "3" },
  { year: "2016", redDelicious: "19", mcintosh: "17", oranges: "5", pears: "7" },
]

Can keys with multiple words be referenced in D3/JS? For example, if we want the key to be "Red Delicious" instead of "redDelicious"

  var data = [
      { year: "2006", red Delicious: "10", mcintosh: "15", oranges: "9", pears: "6" },
      { year: "2007", red Delicious: "12", mcintosh: "18", oranges: "9", pears: "4" },
      { year: "2008", red Delicious: "05", mcintosh: "20", oranges: "8", pears: "2" },
      { year: "2009", red Delicious: "01", mcintosh: "15", oranges: "5", pears: "4" },
      { year: "2010", red Delicious: "02", mcintosh: "10", oranges: "4", pears: "2" },
      { year: "2011", red Delicious: "03", mcintosh: "12", oranges: "6", pears: "3" },
      { year: "2016", red Delicious: "19", mcintosh: "17", oranges: "5", pears: "7" },
    ]

UPDATE: When trying to reference "Red Delicious" it returns as undefined. Refer to this jsfiddle for clarification (data displays as "undefined" on mouseover).

var rect = groups.selectAll("rect")
      .data(function(d) { return d; })
      .enter()
      .append("rect")
      .attr("x", function(d) { return x(d.x); })
      .attr("y", function(d) { return y(d.y0 + d.y); })
      .attr("height", function(d) { return y(d.y0) - y(d.y0 + d.y); })
      .attr("width", x.rangeBand())
      .on("mouseover", function() { tooltip.style("display", null) })
      .on("mouseout", function() { tooltip.style("display", "none"); })
      .on("mousemove", function(d) {
        var xPosition = d3.mouse(this)[0] - 15;
        var yPosition = d3.mouse(this)[1] - 25;
        tooltip.attr("transform", "translate(" + xPosition + "," + yPosition + ")");

        tooltip.select("text").text("Apple: "+d['red Delicious']);
      });

It would be beneficial to identify the key (in this case, "Red Delicious") of the current value being charted using something like

.text(d.key+": "+d.y) // where d.key is the correct way to find d's key

Answer №1

After transforming your dataset for the d3.layout.stack() layout, you may have noticed that the information about the fruit names was lost.

If you check the contents of the dataset by using console.log(dataset), you'll see that it consists of 4 arrays, each representing a different fruit. Inside each array are objects with x and y values for the data points. It's important to keep track of the fruit name as well:

var dataset = d3.layout.stack()(["red Delicious", "mcintosh", "oranges", "pears"].map(function(fruit) {
  return data.map(function(d) {
      return {x: parse(d.year), y: +d[fruit], "fruit":fruit};
  });
}));

By including the fruit property in each data point, you can easily reference it in your tooltip text using d['fruit']

Check out this updated version of your fiddle: http://jsfiddle.net/j3qrd3z7/3/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Conflicting issues with jQuery's load() method

I am facing an issue with loading two HTML pages into a single div. I have index.html and try.html in the root folder, where try.html is loaded into index.html's div (#content) when Button 01 is clicked on index.html. The problem arises when I further ...

On my webpage, there are two buttons labeled "Save" and "Complete". I am in need of creating two distinct alerts for each of the input fields

If the user does not enter a value in the input box for charge_amt, I have set up an onbeforeunload jQuery event to notify them. Once they enter the amount, they will be able to save. <td><input type="hidden" name="charge_cc" value="0" class=""&g ...

Switch up the position of the vertex shader in Three.js/webgl

I've been working on a particle system using three.js that involves using regular JavaScript loops to change particle positions, but I've found that this method is quite slow. Due to this performance issue, I've decided to delve into transf ...

Sleek transitions for navigating between cells in a data table

I am looking to implement a smooth animation for cell navigation. Check out what I currently have: http://jsfiddle.net/0ardb3u0/ When the mouse hovers over a cell, I want the full column and row of that cell to be selected and highlighted in blue. How ...

Enhancing code branch coverage using Istanbul

The code snippet provided has a branch coverage of only 50% (refer to the coverage report below). I am unsure how to enhance this as there are no if statements present. I suspect that Istanbul must utilize some form of measurement that I have yet to grasp ...

Utilize the clearChart() function within Google charts in conjunction with vue-google-charts

I have integrated vue-google-charts to display various charts on my website. I want to allow users to compare different data sets, by enabling them to add or delete data from the chart. In order to achieve this functionality, I need to find a way to clear ...

Using Node.js: Interacting with npm inside a module

Is there a more efficient way to implement self-updating functionality for a globally installed module than using the code snippet below? require("child_process").exec("npm update -g module-name"); I came across some documentation regarding installing np ...

Determine the precise x and y coordinates of a centered element using JQuery

How can I determine the exact left and top positions of an element? The parent container has text-align: center, causing potential confusion when there are multiple elements on the bottom row. For instance, the first one may have a position of 0px instea ...

Create an array where the second dimension can dynamically add any number of values using the append method

What is the best way to create an array with a fixed first dimension of 5 while allowing for varying second dimensions? In other words, how can we initialize an array called arr with five entries and dynamically add elements to each entry like adding val ...

writing a react element in an object with an svg component

I am encountering difficulties when trying to type the following. The problem lies with the TeamIcon. Here is how my object is declared. import TeamIcon from './components/icons/TeamIcon'; export const teamObject: Record< string, Recor ...

Sending the handleSubmit() function to the child component does not alter the state of the parent component

I just started learning React and Javascript. Currently, I am working on a form where users can specify the details of a "Mob". Upon submitting the form, I anticipate that handleSubmit() (which is passed down from the parent component) will update the sta ...

Despite successfully retrieving the response from the YouTube API Fetch, I am unable to access the items

Many questions regarding this issue focus on having the wrong key, but I believe my key is correct. Now I am confused whether the problem lies with the YouTube API or the fetch() method. In simple terms, I am sending the following request: export functio ...

ways to verify ng-if post modification occurrence

Currently, my project is utilizing Angular 6. In the code, there is a div element with *ng-if="edited" as shown below: <div *ngIf="edited"> {{langText}} </div> Initially, when the page loads, edited is set to false and the div is not vis ...

Nextjs is not updating the Redux api state

I am working on a vehicle form component where users can select the year, make, and model of their vehicle. When a user selects the year, I trigger a Redux action to fetch all makes for that specific year. Subsequently, when the user selects a make, anothe ...

How to search for a value in Firebase database and save it to an HTML table?

I am working on fetching specific values from my 'snapshot' and storing them if they exist. Below is the snippet of my code: function paydata(){ firebase.database().ref("pay/0/0/").once('value', function(snapshot){ var resp ...

Struggling with customizing the style of react mui-datatables version 4

Currently, I am utilizing "mui-datatables": "^4.2.2", "@mui/material": "^5.6.1", and have attempted to customize the styling in the following manner: Refer to the Customize Styling official documentation for more details // CUSTOMIZING MUI DATATABLES imp ...

What is the best way to initiate an onload event from a script embedded within a jquery plugin?

Currently, I am in the process of developing a jQuery plugin. One issue that I have encountered involves a script tag being dynamically added for LivePerson.com. The script is supposed to trigger an onLoad function specified in the configuration. However, ...

Controller unable to properly increment values

$scope.isChecked = function(id){ var i=0,j=0,k=0; //$scope.abc[i].usertype[j].keywords[0].key_bool=true; if($scope.abc[i].type_selected == true){ while($scope.abc[i].usertype.length){ while($scope.abc[i].userty ...

Implement a feature that adds a circle element when an image is clicked in a React application

I am attempting to create a program that allows users to add circles to an image by clicking on it. Essentially, when the user clicks at coordinates (x,y), a circle with a radius of 10 will appear at that location. I am exploring ways to implement meta-pro ...

Alternative method for displaying text in Discord

At the moment, my discord bot is set up to read from a file and post the new data in that file to a specific channel. I am interested in modifying the output so that any characters enclosed in ~~ are displayed as strikethrough text. const Bot = require( ...