Convert CSV into an object with additional attribute

I'm attempting to import data from a CSV file into a d3 tree graph. While I've successfully loaded the JSON version of the data, the d3.csv parser isn't returning the expected string.

Some approaches I've tried include:

treeData.forEach(function (d) { 

and:

data.map(function(d) { return [ d[" "],

However, these methods reference specific header strings.

I need to structure the d3.csv result like this:

{name: "root", children: []}

and avoid using jsontostring function.

Below is the code snippet I have been using along with the results in the Chrome console:

treeJSON = d3.json("test.json", function(error, treeDataJSON) { console.log(treeDataJSON); });

result: {name: "root", children: Array(6)} children: Array(6) 0: {name: "A", values: "v1", more values: "v7"} 1: {name: "B", values: "v2", more values: "v8"} 2: {name: "C", values: "v3", more values: "v9"} 3: {name: "D", values: "v4", more values: "v10"} 4: {name: "E", values: "v5", more values: "v11"} 5: {name: "F", values: "v6", more values: "v12"}

treeCSV = d3.csv("test.csv", function(error, treeDataCSV) { console.log(treeDataCSV); });

result: (6) [{…}, {…}, {…}, {…}, {…}, {…}] 0: {name: "A", values: "v1", more values: "v7"} 1: {name: "B", values: "v2", more values: "v8"} 2: {name: "C", values: "v3", more values: "v9"} 3: {name: "D", values: "v4", more values: "v10"} 4: {name: "E", values: "v5", more values: "v11"} 5: {name: "F", values: "v6", more values: "v12"}

Answer №1

The solution is actually quite simple: in the callback function, create a literal object and utilize the parsed data (referred to as treeDataCSV) to assign the children property:

const treeData = {
    name: "root",
    children: treeDataCSV
};

Here's a basic demonstration using d3.csvParse instead of d3.csv, while still following the same solution methodology:

const csv = `name,values,more values
A,v1,v7
B,v2,v8
C,v3,v9
D,v4,v10
E,v5,v11
F,v6,v12`;

const treeDataCSV = d3.csvParse(csv);

const treeData = {
  name: "root",
  children: treeDataCSV
};

console.log(treeData)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

Additionally, it's important to note that with your use of d3.csv, you are working with D3 V4 or an earlier version. With that in mind, you should not execute treeCSV = d3.csv(etc... as shown. For more information on this, refer to: d3.json doesn't return my data array in D3 v4

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

Control the scope value using an AngularJS directive

I have a model with values that I need to modify before presenting them to the user. I have checked the documentation but might be overlooking something. For example, I would like to format my variable in this way: <span decode-directive>{{variable ...

Determine whether a div contains any child elements

I am working on a piece of code that checks for the presence of the class "wrong" in any of my divs, and if found, displays a jQuery UI dialog box. My goal now is to enhance this code by adding a condition where it also checks for empty divs before showing ...

What could be the reason my code isn't successfully performing addition within the input field?

As a novice, I am practicing by attempting to retrieve a number from a text field, prompting the user to click a button that adds 2 to that number, and then displaying the result through HTML. However, I keep encountering an issue where NaN is returned whe ...

Is it possible for Angular to perform bidirectional data binding in reverse between two input fields?

I'm struggling to get my two input fields to update values when the opposite input is changed. My goal is to create a simple $dollar to Gold oz calculator with two input fields. You can see a sample preview here: http://embed.plnkr.co/dw6xL95zRqJC1p ...

Check to see if a guest has shown support or followed an outside party

When you already follow a company on Twitter, the "Follow Us" button of that company will automatically turn grey, regardless of the domain. So, how can you determine if User-X is following companies A, B, and/or C based on their Twitter handles? The same ...

Using PhoneGap to load JSON data with the File API when clicking an event

I have successfully developed code that loads JSON data from an external file on the device. The program is designed to work as follows: Upon a click event, it will first attempt to access the local storage file (course.txt) and if it exists, it will read ...

Transform nested arrangements into strings

In my dataset, I have multiple nested dictionaries and lists. My goal is to convert the list into a dictionary where each element of the dictionary does not contain any nested structures. data = [ [ u'abc', u'1.2.3.4', 52, ...

Get your hands on large files with ease by utilizing jQuery or exploring alternative methods

Within my User Interface, there exists an Advanced Search section where the user can select from 7 different options as depicted in the diagram. Based on these selections, a web service is triggered. This web service returns search results in JSON format, ...

Error: The dynamic selection function is experiencing an issue where it is unable to read the "map" property of an undefined

Currently, I am in the process of creating a React component that includes the usage of a select HTML input. The implementation is defined as shown below: <select className="form-control-mt-3" id="clientList" name="clientList" onChange={this.handleC ...

VueJs does not display the source code of components for users

I've recently delved into working with vueJS2 and am currently learning about components. I have a question for the experts in this field. As far as I understand, VueJS processes HTML using JavaScript, which is why the rest of the HTML code may not b ...

When using express, encountering a "Cannot GET / on page refresh" error

Currently working on a small MERN stack project. Managed to deploy it on Vercel successfully and the application runs as expected. Navigating to "/classes" and "/students" using the buttons in the browser works fine, however, upon reloading those pages I e ...

The timer does not stop running even after navigating to a different page

Currently, I am utilizing the yo:angular-fullstack generator for developing my website. After a user registers on the site, an activation email is sent containing a verification link. Upon clicking the link, a message confirming successful activation is di ...

What is the process for converting a JSONObject into a byte array and then back into the original JSONObject?

I have been working with the AWS JSONObject class. For example, let's create a JSONObject object like this: JSONObject obj = new JSONObject(); obj.put("Field1": 35); JSONObject nestedObj = new JSONObject(); nestedObj.put("Name1":"value1"); nestedObj ...

Retrieving & Refreshing Data with ajax and Jquery

I have been working on developing a forum system using jQuery, PHP, Bootstrap, and other technologies. The forum allows users to post, delete, and edit their posts. I have implemented an edit button for the author of the post, which triggers a modal wind ...

Removing an article from a Vue.js localStorage array using its index position

I am facing an issue while trying to remove an item from localStorage. I have created a table to store all the added items, and I would like to delete a specific article either by its index or ideally by its unique id. Your assistance is greatly apprecia ...

NodeJs: Transforming strings into UUID v4 efficiently

Suppose I have the following string: const input = '83e54feeeb444c7484b3c7a81b5ba2fd'; I want to transform it into a UUID v4 format as shown below: 83e54fee-eb44-4c74-84b3-c7a81b5ba2fd My current approach involves using a custom function: funct ...

Error: Unable to access attributes of null object (specifically 'disable click')

Currently, I am integrating react-leaflet with nextjs. Within the markers, there are popups containing buttons that open another page upon click. However, I have encountered an error when navigating to the new page: Unhandled Runtime Error TypeError: Canno ...

Retrieve the information transmitted through a JSON File within NextJS

The code snippet above is currently performing as expected... const [showPosts, setShowPosts] = useState(); async function pullJson() { const response = await fetch(apiUrl); const responseData = await response.json(); displayData = response ...

The sonar scanner encountered an error while attempting to parse a file using the espree parser in module mode

While executing sonar-scanner on a node project, I encounter a Failed to parse file issue, as shown below: ERROR: Failed to parse file [file:///home/node-app/somedir/index.js] at line 1: Unexpected token './AddCat' (with espree parser in mod ...

Gridsome's createPages and createManagedPages functions do not generate pages that are viewable by users

Within my gridsome.server.js, the code snippet I have is as follows: api.createManagedPages(async ({ createPage }) => { const { data } = await axios.get('https://members-api.parliament.uk/api/Location/Constituency/Search?skip=0&take ...