An easy guide to choosing JSON arrays in D3.js using the . operator

I am currently utilizing D3.js to generate a bar chart based on data from a JSON file. My goal is to allow users to filter through various years and countries, but I am struggling to figure out how to select different arrays within the JSON file.

The structure of my JSON data is as follows (which may not be entirely accurate):

var NL = [
    j1996 = [20317, 27395, 29273, 27170, 19441],
    j1997 = [25267, 31331, 35193, 35299, 23005],
    j1998 = [25576, 30643, 35484, 35796, 23343]
]

var BE = [
    j1996 = [52317, 17395, 39273, 47170, 39441],
    j1997 = [35267, 13331, 15193, 15299, 13005],
    j1998 = [15576, 20643, 14284, 25796, 13343]
] 

Furthermore, I have created buttons that trigger the loading of data for different years:

d3.select("#button1996")
    .on("click", function (d, i) {
        bars(j1996);
    })
d3.select("#button1997")
    .on("click", function (d, i) {
        bars(j1997);
    })
d3.select("#button1998")
    .on("click", function (d, i) {
        bars(j1998);
    })

Here is the code for the 'bars' function:

function bars(data) {

max = d3.max(data)

var yScale = d3.scale.linear()
    .domain([0, d3.max(data)])
    .range([0, height])    

var xScale = d3.scale.ordinal()
    .domain(d3.range(0, data.length))
    .rangeBands([0, width], .2)    

var myChart = d3.select("#chart")

var bars = myChart.selectAll("rect.bar")
    .data(data)

//enter
bars.enter()
    .append("svg:rect")
    .attr("class", "bar")
    .style('fill', '#C64567')
    .attr('width', xScale.rangeBand())
    .attr('x', function(d,i){ return xScale(i); })
    .attr('height', 0)
    .attr('y', height)
}

This approach has been successful so far:

    d3.select("#button1996")
    .on("click", function (d, i) {
        bars(NL[0]);
    })

My challenge now is to find a way to toggle between the NL and BE arrays (and possibly more in the future), while keeping track of the last selected year. Any advice on achieving this?

Answer №1

It appears that the issue lies in attempting to define NL as both an array and an object.

Your current declaration

var NL = [
  j1996 = [20317, 27395, 29273, 27170, 19441],
  j1997 = [25267, 31331, 35193, 35299, 23005],
  j1998 = [25576, 30643, 35484, 35796, 23343]
]

produces the same outcome as

var NL = [
  [20317, 27395, 29273, 27170, 19441],
  [25267, 31331, 35193, 35299, 23005],
  [25576, 30643, 35484, 35796, 23343]
]

resulting in an array of arrays. Therefore, trying to access NL.j1996 this way is not possible (in fact, you are assigning each array to a corresponding global variable j199x).

If you intend to use NL as an object, you should follow this syntax:

var NL = {
  j1996 : [20317, 27395, 29273, 27170, 19441],
  j1997 : [25267, 31331, 35193, 35299, 23005],
  j1998 : [25576, 30643, 35484, 35796, 23343]
}

After making this adjustment, accessing NL.j1996 will no longer throw an error.

Answer №2

var NL = [
    j1996 = [20317, 27395, 29273, 27170, 19441],
    j1997 = [25267, 31331, 35193, 35299, 23005],
    j1998 = [25576, 30643, 35484, 35796, 23343]
]

var BE = [
    j1996 = [52317, 17395, 39273, 47170, 39441],
    j1997 = [35267, 13331, 15193, 15299, 13005],
    j1998 = [15576, 20643, 14284, 25796, 13343]
] 

The above format is incorrect. NL and BE should be objects containing arrays as shown below:

var NL = {
    j1996 : [20317, 27395, 29273, 27170, 19441],
    j1997 : [25267, 31331, 35193, 35299, 23005],
    j1998 : [25576, 30643, 35484, 35796, 23343]
}

var BE = {
    j1996 : [52317, 17395, 39273, 47170, 39441],
    j1997 : [35267, 13331, 15193, 15299, 13005],
    j1998 : [15576, 20643, 14284, 25796, 13343]
}

Since NL and BE are objects, you cannot call them like this:

d3.select("#button1996")
    .on("click", function (d, i) {
        bars(NL[0]);
    })

You need to use the following syntax:

d3.select("#button1996")
    .on("click", function (d, i) {
        bars(NL['j1996']); // or 
        //bars(NL.j1996);
    })

Answer №3

It appears that your JSON is not in the correct format. Try using something similar to this structure for easier data access:

 data.NL[0], etc

Your JSON should adhere to the following format:

{
"NL": [{
    "j1996": [20317, 27395, 29273, 27170, 19441],
    "j1997": [20317, 27395, 29273, 27170, 19441],
    "j1998": [20317, 27395, 29273, 27170, 19441]
}],
"NL": [{
    "j1996": [20317, 27395, 29273, 27170, 19441],
    "j1997": [20317, 27395, 29273, 27170, 19441],
    "j1998": [20317, 27395, 29273, 27170, 19441]
}]

}

Remember to validate your JSON using a tool such as http://jsonlint.com/.

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

Issue with the rendering of the Google Font "Playfair Display" involving the letters "ff" being displayed incorrectly

There seems to be a problem with the Google Font "Playfair Display" when two consecutive "f" characters are used. Check out this example of the odd rendering issue My idea for a fix involves creating a JavaScript function that scans all text on the websi ...

Ways to select the nearest element within a designated class

I am attempting to find the closest or nearest class of a specific element. How can I achieve this? I am currently utilizing the .closest method. HTML <div class="test">.test</div> <!-- Not this --> <div> <div class="test ...

Using Java to parse a JSON string and store it in an ElasticSearch database

As a newcomer to ElasticSearch, I am in the process of working with data stored as a Java String in JSON format. My goal is to establish a connection with AWS ElasticSearch and utilize the Java-API to store the information from the String into ElasticSearc ...

Converting Arrays into Objects with Multiple Dimensions

I have been attempting to transform this complex array into an object. However, I am facing an issue where only the second part of the array is being saved in the object, while the first part is missing. Is there a way to ensure that the entire array gets ...

React - warning - Avoid using <Link> outside of a <Router> context

Warning: Invariant failed: It is not recommended to use <Link> outside of a <Router> Encountering this while attempting to write a test for a component where test("renders post list div ", () => { const posts = [ { created: ...

Exploring the output files of C programs using JavaScript

I have been attempting to link two programs I created. One is a C program that generates files on my local disk, and the other is a web program designed to display the contents of these files on screen by accessing them from my disk. Despite trying vario ...

Encoding special characters

When working with JSON to exchange data between systems, I often encounter rich text properties. While most of the time everything goes smoothly, occasionally special characters like curly quotes that are not in UTF-8 format slip into the text. I am looki ...

jQuery Problem: Iterating over each element and executing a function

Currently facing an issue with running a function through .each in jQuery. It doesn't seem to be selecting the element properly using 'this'. Here is the code: (Edit: I am trying to center elements absolutely regardless of screen width, for ...

Subclass callback with parameters

Having some trouble with one of my TypeScript functions and I'm hoping it's not a silly question. I believe what I'm attempting should work in theory. Here's a simplified version of my issue to demonstrate where the problem lies (the o ...

Combine and loop through character arrays

I am attempting to combine two char arrays character by character. To illustrate, consider the following scenario: both[10] | |______both[0] |_____one[0] | both[1] |_____two[0] | bo ...

How to update a dynamic list or array in Flutter using setState()?

Although I'm still new to flutter and struggling a bit with understanding state management compared to React, I've encountered some challenges in handling array variables. When attempting to setState with a different approach, I end up with unexp ...

Exporting a MongoDB query to extract a particular field from a JSON object nested within a JSON array

In my current project, I need to extract specific fields from a JSON object within a JSON array. Let's consider a scenario where there are multiple documents in a collection like the one below: { "_id" : Object("sddf3r"), "ite ...

The event for 'deviceready' in Cordova is not getting triggered when placed inside the angular .run block

Recently, I've been facing difficulties in getting 'deviceready' to register within AngularJS. It was functioning properly earlier, so I'm puzzled about what might have altered. If I trigger 'deviceready' from a global addEve ...

What is the solution to setting true and false equal to true in an AngularJS expression?

How can I determine if an input field has been touched and is empty, without using the built-in functions in Angular? <form-input is-invalid-on="isTouched && !gs.data.name || gs.data.name.length > 50"></form-input> If isTouched &am ...

Find the differences between two String[] arrays and display the distinct strings

I have a folder with a list of file names and another list of files that have been manually checked by a developer. How can I compare these two arrays to only print out the files that are not in the master list. public static void main(String[] args) th ...

Dominating React Components with Unique CSS Styles

Currently, I have developed a NavBar component. I've implemented some JavaScript code that changes the navbar's background color once it reaches 50px. However, I am facing an issue in applying this scroll effect to only one specific file and not ...

transmit information from a Node.js server to Ajax

Is it possible to verify if a user-entered token exists? Here is my Node.js controller: const checkToken = async (req, res) => { const token = req.body.token; User.findOne({'token': token}).then((user) => { if (user) { ...

Transforming a JSON array into arrays of NSNumbers

I successfully obtained information from a JSON web service and organized it into the array below: _soldamount = ( 0, 0, 0, 0, "62.69", "48.3", 81, "59.83", "162.57", 0, "40.67", ) I suspect that this array is ...

What is the best way to retrieve attributes and values from JSON using JavaScript?

I'm working with a javascript function called create(tagName, options), where the options variable is in JSON format. Here's an example structure: {id: 'test_id', class: 'test_class'} My question is about how to extract the ...

Ways to customize decoration in Material UI TextField

Struggling to adjust the default 14px padding-left applied by startAdornment in order to make the adornment occupy half of the TextField. Having trouble styling the startAdornment overall. Attempts to style the div itself have been partially successful, b ...