Transforming data with D3.js into a string representation

Recently, I stumbled upon a function called "stringify" that seems like a fantastic tool for converting flat data into a Json format.

If this function lives up to its potential, it could potentially save me countless hours of writing recursive code in ASP/SQL.

Check out the original code here: Original code

I've been working on creating a similar effect with my own data. I've made some progress, and you can actually run the sample code to see the desired structure.

<script>

var data = [
 { "name" : "A", "parent":"null" },
 { "name" : "J", "parent":"A"},
 { "name" : "I", "parent":"A" },
 { "name" : "G", "parent":"A" },
 { "name" : "H", "parent":"A" },
 { "name" : "Cr", "parent":"B" },
 { "name" : "D", "parent":"Cr" },
 { "name" : "E", "parent":"Cr" },
 { "name" : "H", "parent":"A" },
 { "name" : "F", "parent":"Cr"},
 { "name" : "B", "parent":"A" }
];

// create a name: node map
var dataMap = data.reduce(function(map, node) {
map[node.name] = node;
return map;

}, {});

// create the tree 
var tree = [];
data.forEach(function(node) {
// add to parent
var parent = dataMap[node.parent];
if (parent) {
    // create child 
    (parent.children || (parent.children = []))
        // add node 
        .push(node);
} else {
    // null or missing
    tree.push(node);
}
});


d3.select('body').append('pre').text(JSON.stringify(tree, null, '  '));

Now, I'm facing a challenge in integrating these two components seamlessly.

It's probably something simple, but staring at code and rewriting it after consuming copious amounts of coffee is starting to take its toll.

If any of you experts out there have any hints or suggestions, please feel free to share them. Any modifications or recreations of the existing code are more than welcome. Thank you for taking the time to read through this!

Answer №1

Issue Resolved!

Thanks to a couple of espressos, I was able to figure out how to make it work.

It may be a bit of a patchwork solution, but it gets the job done - for now, that's all that matters to me.

By using the code snippet

  JSON.stringify(tree, null, '  ')

I was able to directly swap out the original string with var n = ...

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

Is there a specific JSON schema designed for the SurveyMonkey API?

Currently, I am using the SurveyMonkey API to write Java code for survey analysis. The API provides JSON data which I need to manipulate efficiently and safely in my code by generating specific Java classes. However, despite my efforts, I have been unable ...

Transferring Information Between Vue Components

In my project, I have implemented 3 Vue components to work together seamlessly. Component A is responsible for listening to an event triggered by a user clicking on HTML text and storing the data into a variable. Component B utilizes this data to make an A ...

What is the best way to check for a matching array value in my menu list and apply a corresponding class tag to it?

I need a way to dynamically add a class to tags that match specific array values. My menu list consists of 150 items, and I want to add a class to the tag whose text matches an element in the array. <ul class="nav main" id="tabs"&g ...

Error: anticipated expression, received keyword 'if'

I'm facing an issue that I could really use some assistance with. I am trying to hide the "changeOrderUp" button when it's in the first row, and similarly, I want to hide the "changeOrderDown" button when it's in the last row. However, FireB ...

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

Direct the /username path to /[user]/[tab].js instead of [user]/index.js in Next.js

My goal is to develop a user profile page that displays content based on the current tab the user is viewing. The tab is determined by what is provided in the URL (e.g. /username/tab1). The challenge I am facing is that one of the tabs the user can access ...

Can we create a command that searches for the argument input in a JSON file and then displays all the findings in a Discord embed?

I'm working on a command where users can enter the name of a state as an argument. The client then searches through the voter.json file to find dictionaries with the matching state. Currently, the code is functioning but it sends each result in a sepa ...

Can the color of text be adjusted (to either white or black) based on the background color (in any color and format)?

To achieve a text color that contrasts well with any background, I need to make sure it's either black or white. The background in my app can vary in color and format, so finding the perfect solution has been challenging. Using mix-blend-mode doesn&a ...

Tips for concealing the Bottom bar action in React Native

Currently facing an issue with React Native - I need to hide the bottom action bar located just below my tab bar navigation. I'm trying to create a clone of the Disney + App and this particular problem has me stuck: Here's the bottom part of my ...

Remove background image when input form field is in focus

I am currently experimenting with the following approach: $('input').on('click focusin', function() { $('.required').hide(); }); However, it appears that this logic is not functioning as intended. Here is an ...

Converting an onclick event to onsubmit: Tips for doing it right

Recently, I had to add validation to a file upload form for our Google Drive. After some research, I discovered that using onsubmit instead of onclick was the way to go. However, when I made the switch from onclick to onsubmit, the validation worked but t ...

Checking for the existence of a row in Node.js using Sqlite3

Wondering if it's possible to verify the existence of a row using node.js and the sqlite module. I currently have this function in place, but it always returns false due to the asynchronous nature of the module. function checkIfRowExists(username, pa ...

What could be the reason behind TypeScript ignoring a variable's data type?

After declaring a typed variable to hold data fetched from a service, I encountered an issue where the returned data did not match the specified type of the variable. Surprisingly, the variable still accepted the mismatched data. My code snippet is as fol ...

The ngOnChanges lifecycle hook is triggered only once upon initial rendering

While working with @Input() data coming from the parent component, I am utilizing ngOnChanges to detect any changes. However, it seems that the method only triggers once. Even though the current value is updated, the previous value remains undefined. Below ...

Maintaining the consistent structure of build directories within a Docker container is crucial, especially when compiling TypeScript code that excludes the test

Our application is built using TypeScript and the source code resides in the /src directory. We have tests located in the /tests directory. When we compile the code locally using TSC, the compiled files are deposited into /dist/src and /dist/test respectiv ...

The Javascript array does not function like a typical array

I am currently facing a perplexing issue while working with the Twitter API. Below is the script causing the confusion: const Twitter = require('twitter-api-stream') const twitterCredentials = require('./credentials').twitter const t ...

Currently, I am attempting to retrieve text input through the use of AngularJS

Having trouble retrieving text input values using Angular JS? The console keeps showing undefined. <div ng-controller="favouritesController" class="col-xs-12 favList"> <input type="text" ng-model="newFav" ng-keyup= "add($event)" class="col-xs-1 ...

Apache causes HTML download tag to malfunction

I have an HTML file that includes the following code: <a href="/Library/WebServer/Documents/file.zip" download="file.zip"> Download here </a> When I test this HTML page on Chrome, it successfully allows me to download the file. However, when ...

Change the behavior of a submit button to trigger a custom JavaScript function instead

I am faced with a challenge where I need to override the default functionality of a button in code that cannot be altered. Instead, I must ensure that when the button is clicked, a custom JavaScript method is called rather than submitting the form as it no ...

Tips for creating a secure authentication system in an AngularJS application!

As a novice in the world of angularjs... After going through the documentation and completing a tutorial, I decided to experiment on my own which has helped me grasp things better. Now, I'm looking into creating a secure authentication system. The ...