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

The Autocomplete feature in Material-UI is not rendering any output

Within the render method of a class, an Autocomplete component is causing nothing to appear as rendered; once removed, everything else renders as expected. export default class Home extends Component { render() { return ( ... ...

What is the best way to structure a JSON response in python code?

Here is a sample of my JSON data: data = [{"document_id":"FT_3860001798686","party_type":"1","name":"LEE, GABRIEL"},{"document_id":"FT_3860001798686","party_type":&qu ...

Adjust the placement of the fixed header waypoint or change its offset

Currently working on developing a Wordpress site with the Avada theme, my goal is to have a sticky header that starts immediately at the top of the page. This is the website in progress: The site I'm trying to emulate is synergymaids.com. If you vi ...

Unsynchronized AJAX POST requests fail to function effectively

I am encountering an issue with an AJAX call that I am using to log in a user. Here is the code: function loginUser() { var xmlhttp; if(window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest() ...

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 ...

How can we prevent the modal from extending beyond the boundaries of the phone screen when zoomed in

I am currently developing a web application that features a large content page, specifically a map which should display detailed information upon zooming in similar to Google Maps. The interactive elements on my map are clickable, triggering a modal popup ...

A guide on accessing the first element in an array when performing multiplication within the Interval component in React.js

I am having trouble initiating an if statement from number 0 once the window is loaded, as it seems to be skipping over 0 and starting from 1 instead. Can someone please assist me in understanding how this works? showAnime = () => { let counter ...

Tracking the number of form submissions on a PHP website

I am looking to add a counter feature to my website where every time a form is submitted, the count increases for all visitors. The starting number will be 0 and each form submission will increment the count. While I can manage the count using JS/jQuery w ...

Is there a way to retrieve just the array element as the output instead of the entire object in MongoDB?

Here is the code snippet I am using to display review array data from the restaurant collection object: async get(reviewId) { const restaurantsCollection = await restaurants(); reviewId = ObjectId(reviewId) const r = await restaurantsCollect ...

Babylon entities failing to run

Encountering a strange issue in my current project. I am working on a react application that incorporates Babylonjs for 3D rendering. While I am able to successfully load objects into the scene, I am facing a problem when attempting to create a PBR Materia ...

Choose a dynamically generated html element without having to click on it

I've been looking for a way to target a dynamically-generated element (specifically a div with the class "date") using jQuery. While I keep finding references to the .on('click') method, it appears that this only selects the div once the pag ...

Tips on efficiently compressing JSON data in order to receive it using the bodyParser.json method

I am looking to compress a JSON file before sending it to my server. I want to handle the compression in the browser by utilizing an explainer and then pass it to the bodyParser.json middleware. The client-side function would look something like this: e ...

Retrieve the data from every dropdown menu

How can I retrieve the selected values from all created selects when a button is clicked? I have attempted using both refs and v-model, but neither of them are functioning as expected. <div v-for="attribute in attributes" class="col"> {{ a ...

Is it possible to verify if each input is unique using the parsley validator?

As a novice, I am struggling with a task where I have 6 School Children IDs. The teacher needs to input these IDs, and while it's not vital for him to enter all of them, he must input at least one. Furthermore, if he decides to input more than one ID, ...

What is the best method for extracting information from this data? (extracting data from

I need assistance. I've written multiple arrays to a text file and now I'm trying to parse them. What am I doing incorrectly? fs.readFile("./data.txt", "utf8", function(error,dataRes){ console.log('Reading data') ...

The AJAX post request is returning an undefined value

I'm working with JavaScript, AJAX, and Node.js but I'm having trouble receiving a value on the server side when making a POST request. Despite my efforts to test it out, the console keeps returning 'value undefined'. Here's a snip ...

Next.js configuration: Redirecting / to the basePath

Whenever a user accesses the path /, I need it to redirect to the basePath that has been previously set. Below is my configuration in next.config.js: module.exports = { basePath: '/docs', } This means that whenever the path / is visited, it s ...

Display the full price when no discount is available, but only reveal the discounted price when Vue.js is present

In my collection of objects, each item is structured like this: orders : [ { id: 1, image: require("./assets/imgs/product1.png"), originalPrice: 40, discountPrice: "", buyBtn: require(&q ...

Issue: Infinite loops detected in AJAX functions

I am using $.get methods in the following code snippet: $.get("/url" , function(z) { var a = $(z).find("span"); for (var i = 0 ; i<a.length; i++){ var v = $(a).eq(i).children("strong:first").text(); alert(v); } }); However, the s ...

Utilizing fluent-ffmpeg in nodejs and express to effortlessly download a video

I've been recently tackling a side project that involves downloading videos from Reddit. The tricky part is that the video and audio are stored in separate files, requiring me to merge them before being able to download them onto the client's dev ...