The unexpected disappearance of data in a d3 v4 map leaves users puzzled

My current task involves reading data from a csv file and creating a map where the key is the state abbreviation and the value is the frequency of that state in the data.

The code I have successfully creates the map, reads in the data, and when I use console.log(MAP), it outputs correctly.

However, I encounter an issue when I attempt to iterate through the map using .each or .entries() as the map appears to be empty. The method map.size() returns 0.

var statesData = d3.map();
d3.csv("temp-data.csv", function(error, data) {
    if (error) throw error;
    data.forEach(function(row) {
        if (statesData.has(row.state) == false) {
          statesData.set(row.state, 1);
        }
        else {
          statesData.set(row.state, statesData.get(row.state) + 1);
        }
    });
});
console.log(statesData);
console.log(statesData.size());
statesData.each(function(d) {
  console.log("value: " + d);
});

Output:

{}
"$AZ": 1
​
"$CA": 1
​
"$CO": 1
​
"$IA": 1
​
"$KS": 2
​
"$OK": 1
​
"$OR": 1
​
"$PA": 1
​
"$WA": 1
​
<prototype>: Object { constructor: Map(), has: has(), get: get()
, … }
0

https://i.stack.imgur.com/7pWYf.png A picture is also attached for clarification.

temp-data.csv:

id,state,
3,WA
4,OR
5,KS
8,CA
9,CO
11,OK
13,AZ
15,KS
16,IA
17,PA

Although the map contains data, calling .size() results in 0, thus explaining why the .each() method does not output anything.

I am puzzled by this situation and have tried referring to the documentation at but still can't figure out why I can successfully log MAP but cannot iterate through it.

Thank you!

Answer №1

Understood:

Understanding variable scope in d3 javascript

It's important to note that the d3.csv function operates asynchronously, meaning any code relying on its data should be contained within its scope.

This clarifies why the value of statesData is 0 when accessed outside of the d3.csv scope.

The snippet below demonstrates this concept:

var statesData = d3.map();
d3.csv("temp-data.csv", function(error, data) {
    if (error) throw error;
    data.forEach(function(row) {
        if (statesData.has(row.state) == false) {
          statesData.set(row.state, 1);
        }
        else {
          statesData.set(row.state, statesData.get(row.state) + 1);
        }
    });

    console.log(statesData.size())
});

When executed, it correctly displays a size of 9.

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

Utilizing internal PDF links in a Microsoft UWP application

In the process of developing a UWP app using javascript, I have created a list of links that are connected to PDF files stored locally in the app. The ultimate goal is to offer a collection of hands-free documentation for the Hololens (Windows AR) device. ...

Tips for Utilizing CSS Overflow: Hidden to Prevent the Parent Container from Expanding

I have a fixed width column and a fluid column. In the fluid column, I want to display a string with nowrap so that it does not overflow the container. Here is an illustration of how I want the text to appear: --------------------------------------------- ...

The jQuery AJAX response consistently comes back empty

Hello, I'm currently working on creating an HTML form and I need to validate it before submitting the form action. However, when I use AJAX to respond, I keep receiving a blank message. Can anyone help me with this issue? $(function(){ $("#ajax-p ...

A comprehensive guide to navigating pages using AngularJS

Greetings! I've recently embarked on my Angular JS learning journey and have encountered an issue with loading content from pages. Unfortunately, I am not able to receive any content. Below are snippets of my index file and corresponding JavaScript co ...

What steps can you take to prevent a potential crash from occurring when an unauthorized user attempts to access a page without logging in?

I've encountered an issue where the app crashes when trying to access a page that requires logging in. The reason for this crash is because the page attempts to load undefined data, resulting in the error: TypeError: Cannot read property 'firstN ...

When I click, I expect to retrieve the tr element, but instead, I am receiving the td element

When I have a table and click on a tr element, the function returns a td element instead. Can someone explain why this is happening? let func = function () { $("tr").on("click", (event) => { event.preventDefault(); event.stopPropaga ...

Step-by-step guide on integrating a specific location into Google Maps using React.js

I'm in the process of revamping my website using Reactjs. I want to incorporate a specific Google location with reviews on the map, similar to how it appears on this example (My current website is built on Wordpress). As of now, all I've been ab ...

Error: The function Object.setup() is undefined

I'm having an issue with my JavaScript setup function and array of ghost objects called ghosts. When I try to call the setup function on the last ghost object in the array, I receive this error message: Uncaught TypeError: ghosts[(ghosts.length - 1)]. ...

Executing a JavaScript function across multiple elements: A step-by-step guide

I recently came across this code snippet on w3schools.com: <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> * {box-sizing: border-box} body {font-family: Verdana, ...

The function to set the state in React is malfunctioning

I'm currently in the process of developing a website where I utilize fetch to retrieve information and display it to the user. Initially, I opted to save this data in a state variable, but for some reason, it's not functioning as expected. Upon ...

Navigating the Google Maps API: Implementing Scroll Zoom to Focus on a Single Marker

I'm looking for a solution for my project where the scroll zoom function will focus on zooming in on a marker or specific point rather than defaulting to the cursor. The current behavior is that the scroll zoom always centers on the cursor. Can anyone ...

Why does the Node promise chain execute .then despite encountering an error?

When a promise chain encounters an error, why does it not execute .then unless the .then references an external method with a parameter? In this particular example, I intentionally throw an error in the promise chain. The first three .then methods do not ...

Accordion jQuery failing to display tabs

I have a question about using 2 jQuery accordions with tabs inside them. Everything seems to be working, but when I try to expand the second accordion, the two tabs inside don't render properly. I'm not sure what the issue is. Any help on this wo ...

Exploring the intricacies of defining Vue component props in TypeScript using Vue.extend()

Here is a simple example to illustrate my question When I directly define my props inside the component, everything works fine <script lang="ts"> import Vue, { PropType } from "vue"; export default Vue.extend({ props: { col ...

Why does Visual Studio Code auto-complete "ImagePropTypes" when typing a dot after "props"?

Currently following a React Native tutorial with Visual Studio Code. Using Babel Javascript as my selected language mode. Encountering an issue when typing Line 7: https://i.stack.imgur.com/WcV7B.png After adding a period (.) to props, it changes to Ima ...

Struggling to efficiently handle imported JSON data using VUE.JS JavaScript?

Struggling to extract specific information from JSON data that I need to import. Here is the sample data I'm working with: I am trying to extract details like the name, description, and professor for each entry. This is how I'm importing the d ...

What is the best way to create a sleek typewriter effect transition by hovering between tabs?

When hovering over a tab, the content in the main content area's child div should be displayed from a sibling div that holds the content. Initially, the details div style is set to hide the contents but upon hover, it is displayed. The described func ...

Upload an image to a Node.js API using the Next.js API directory

I am working with a file instance that I obtained from the formidable library. Here's how it looks: photo: File { _events: [Object: null prototype] {}, _eventsCount: 0, _maxListeners: undefined, size: 16648, path: 'public/ ...

The HTML is not rendering as planned

I have 2 files, test.html <!DOCTYPE html> <head> <title>test</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script src="./test/jquery.min.js"></script> </head> <body> ...

What is the best way to display a PDF in a web browser using a JavaScript byte array?

I have a controller that sends the response Entity as a byte array in PDF form to an ajax call. However, I am struggling to display it in the browser despite trying various suggestions from old Stack Overflow questions. Here is the response from the Sprin ...