Exploring the world of two-dimensional arrays in D3 programming

I am interested in visualizing data obtained from the census data API, specifically from the ACS survey.

The data is not in a typical JSON format, but rather as a two-dimensional array. It appears like this:

[
[
    “POPULATION”,
    “DATE”,
    “ANOTHERTHING”
],
[
    “ALABAMA”,
    “2000”,
    “MORESTUFF”
],
[
    “ALASKA”,
    “2000”,
    “OTHERSTUFF”
],
…
]

I have limited experience working with JSON data like this, which resembles more of a CSV structure with keys on the first line and values following in subsequent lines.

Does anyone know how to parse and manipulate this kind of data in D3, without needing to convert it beforehand (such as using a tool like https://gist.github.com/sarfarazansari/7e8ae05168b80b36016eb1c561a82f73)? I prefer to directly utilize the data from the API.

Any assistance or advice on this matter would be highly appreciated.

Answer №1

Before anything else: avoid using smart quotes () in JSON (or any code for that matter). It seems like the issue with your JSON is due to using a text editor like MS Word. Also, there's no such thing as "non-standard JSON" since there isn't a standardized format to begin with. Your JSON is simply an array of arrays, nothing out of the ordinary.

That said, you can work with this data structure to create your charts. But if you're new to this, it might be best to follow the common way of organizing data in D3 codes – using an array of objects.

You can easily convert your array of arrays into an array of objects for easier handling:

Assuming your array is named data, let's first extract the headers:

var keys = data.shift();

This will not only create a headers array but also remove the first inner array from the data.

Next, iterate over each inner array to create objects with the necessary key/value pairs:

var newData = data.map(function(d) {
  var obj = {};
  d.forEach(function(e, i) {
    obj[keys[i]] = e;
  });
  return obj;
});

There are more concise ways to achieve this, but the above method is clearer and more educational.

Here's a sample demo using the shared data:

var data = [
  [
    "POPULATION",
    "DATE",
    "ANOTHERTHING"
  ],
  [
    "ALABAMA",
    "2000",
    "MORESTUFF"
  ],
  [
    "ALASKA",
    "2000",
    "OTHERSTUFF"
  ]
];

var keys = data.shift();

var newData = data.map(function(d) {
  var obj = {};
  d.forEach(function(e, i) {
    obj[keys[i]] = e;
  });
  return obj;
});

console.log(newData)
<script src="https://d3js.org/d3.v5.min.js"></script>

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 Multiple File Upload Functionality in Dropzone.js + Laravel (Only allowing one file to be uploaded)

Looking for assistance in uploading multiple files using AJAX with Dropzone.js plugin. This is what I have implemented so far - HTML (view)- <div class="dropzone" id="add-slide-image"> </div> JS- Dropzone.autoDiscover = false; var myDropzo ...

Is it possible to call a JavaScript file located inside a Maven dependency's jar?

In the process of developing a Spring MVC web application using Apache Tiles, I have incorporated JavaScript libraries such as JQuery by including them in the pom.xml file as dependencies. My query pertains to whether I can access these scripts from within ...

How can I ensure my AngularJS Controller variable is accessible across all page contexts?

Working with AngularJS, I have a view controller where I initialize a variable called recipesData. Here is the code for the controller: (function() { 'use strict'; angular .module('myApp') .controller('Coo ...

Create a roster of numbers that are multiples using a systematic approach

Is the following code a functional way to return multiples of 5? function Mul(start,array,Arr) { Arr[start]=array[start]*5; if(start>array.length-2){ return Arr; } return Mul(start+1,array,Arr); } var numbers =[1,2,3,4,5,6 ...

Which HTTP headers pertain to the loading of iframes? nuxt-helmet

Can anyone explain which security headers are associated with iframe loading issues and may prevent the iframe from being loaded? I implemented nuxt-helmet to configure security headers in my nuxt project. However, after uploading my site to a server loca ...

Is it possible to invoke an AngularJs service by clicking a button?

Recently, I've been working on some AngularJS code involving a service and controller. angular.module('myModule', []).service("AttendanceService", function ($http) { this.getdata = function () { return $http({ ...

What is the correct way to parse a JSON array of arrays using the Jackson JSON parser?

I have an API that generates the following JSON: { "monitors": [ [ "/Common/http-cc-ping-any" ] ], "is_alive":true } I am attempting to utilize Spring and Jackson JSON Parser to map this JSON to a POJO. The POJO i ...

Is there a way to invoke a JavaScript function specifically for a given link?

I am trying to make the JavaScript only apply to a specific A LINK (#tornado,_bar -> ul -> li -> a links) when clicked, but it is applying to all A links. How can I specify the particular link in the JS? The JavaScript code is not functioning cor ...

The CustomValidator ClientValidationFunction will only activate on the second or subsequent submission if CheckBoxList is checked

I am encountering an issue with a user control that is dynamically added to pages on DNN. The user control is built on a customized version of CheckBoxList and includes a CustomValidator with ClientValidationFunction set to a javascript function. It works ...

Troubleshooting: Issue with append function not functioning properly after click event in Angular

I am struggling to implement a basic tooltip in AngularJS. Below is the HTML I have: <span class="afterme" ng-mouseover="showToolTip('this is something', $event)" ng-mouseleave="hideToolTip();"> <i class="glyphicon glyphicon-exclama ...

What is the best way to implement a date range filter in AngularJS for a specific year or month?

I am just starting to learn AngularJS. I have a date formatted as follows: d MMM y. However, I have two fields - one called "from" and the other "to" - that should act as filters for the date range, based on a year range or month range. Here is how I am or ...

"Key challenges arise when attempting to execute the node app.js script through the terminal due to various middleware compatibility

I'm a beginner with node.js and I've encountered an issue while trying to run my node app.js file after incorporating a new file named projects.js which contains the following JS code: exports.viewProject = function(req, res){ res.render(" ...

Does ECMAScript differentiate between uppercase and lowercase letters?

It has come to my attention that JavaScript (the programming language that adheres to the specification) is sensitive to case. For instance, variable names: let myVar = 1 let MyVar = 2 // distinct :) I have not found any evidence in the official specific ...

Using Firefox to cache Ajax calls after navigating back in the browsing history

Currently, I am utilizing an ajax call to invoke a php script that waits for 40 seconds using sleep and then generates the output RELOAD. Subsequently, in JavaScript, the generated output is validated to be RELOAD, following which the call commences again. ...

Link up each query with every php echo

Suppose I have the following PHP code: $logger = $_SESSION['logger']; $postquery = $con->query("SELECT * FROM posts ORDER BY id DESC LIMIT 5"); while($row = $postquery->fetch_object()){ $posts[] = $row; } And then, this section of ...

Using Python Selenium to create a login page with Javascript

Attempting to access a page using Python selenium package for certain activities is proving challenging. Despite the following code being written, an error message of "the Class is not found" keeps appearing. To proceed with using send_keys(), it's ne ...

Spin the object around the z-axis, with the point serving as the center of rotation

I have a unique challenge with positioning a HUD object on the front of a tube in Three.js. The HUD needs to align itself based on a vector point, always facing towards the high side of that point, regardless of the direction and position of the tube. To b ...

What is the process for verifying JSON format validation?

When my program receives a JSON file containing information for a service, I need to verify its validity (checking if all necessary keys exist) before running the service program. The standard JSON format required for this program is as follows: { "se ...

What is the method for inserting data into an array of objects in JavaScript?

I have a question regarding how to push/replace data into an object of an array of objects. Please excuse any mistakes in my grammar. Here is my dummy data: const dummyData = { id: 1, daerah: "Bandung", date:"1668790800000& ...

Efficient Array Comparing Speed

Looking for the most efficient way to compare two sorted arrays of unique values in different data formats? The objective is to eliminate any duplicate values present in both lists. Here is a starting point: int [] array1 = {1, 2, 3, 4, 5}; int [] array2 ...