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

Choose an image to be displayed at either full width or full height, depending on which dimension is reached first

I have a query regarding resizing an image within a div to either 100% width or 100% height of the containing div. Despite setting max-height and max-width to 100% as recommended here, I still encounter overflow issues without wanting to crop the image usi ...

Using Angular's ngBlur directive on multiple input fields

My current task involves capturing and saving all content on a webpage after it has been edited. For example, when a user clicks into an input field, enters data, and then clicks elsewhere, I would like to trigger a function to collect all the model data a ...

Tips for handling ng-if during element presence checks

There's a hidden div on my web page that is controlled by an ng-if directive. I'm looking to create a test that confirms the presence of the element only when it should be visible. If the condition set by ng-if is not met, the element is complete ...

Plugin for creating a navigation bar with a jQuery and Outlook-inspired style

Our team is considering transitioning our asp.net forms application to MVC. Currently, we utilize outlook-style navigation with ASP controls such as listview and accordion, using code referenced here. Are there any jQuery/CSS controls available for MVC t ...

What strategies can be used to effectively structure CSS and JavaScript in a project for optimal organization?

In my NetBeans project, I currently have a large web project with CSS files included in the header. Some CSS codes are needed on all pages, while others are only necessary for specific pages. I am looking to optimize high-traffic pages by removing any ...

What is the process for obtaining a client-side cookie using next.js?

I'm currently facing an issue where I can't seem to maintain a constant value for the isAuthenticated variable between server-side and client-side in next.js. In my setup, I am using a custom app.js file to wrap the app with Apollo Provider. The ...

vue utilize filtering to search through a nested array of objects within a parent array of objects

After making an API call, I receive JSON-formatted data with a specific structure like this: data = [ { name: 'John', school:[ { school_name: 'Harvard', date_attended: '2017-05-23' }, { schoo ...

What are the steps for executing an API and entering data into it?

I have developed an API using NodeJS, ExpressJS and MongoDB to filter and sort school data based on location and fees. The main code snippet looks like this: const express = require('express'); const bodyparser = require('body-parser') ...

What steps can be taken to resolve the issue of "Access Denied: Invalid token, incorrect code"?

Assigned to me recently for a school project is a coding challenge that consists of various parts. The final task involves uploading to a private GitHub repository and submitting a completion request through a POST request under specific conditions. I hav ...

Is there a way to track the frequency of a specific field or name within a JSON file using Python? I am solely interested in the number of occurrences of the name, not the value associated with it

In my text file, I have JSON data with a specific format: { "_id":"123adfvssw", "content_type":"video", "content_id":"12345", "commenter":{ "display_name":"student2", "name":"student2", "type":"user", }, "source":"c ...

React with TypeScript: The struggle of getting LocalStorage to work

Currently, I am dealing with persistence in a todo application developed using React and TypeScript. To achieve the desired persistence, I have implemented localStorage. Allow me to share some code snippets: const [todos, setTodos] = useState<todoMod ...

Tips for utilizing the for each function within a for loop

Looking to showcase prices alongside each product based on their unique sku value, I've put together a price list. An array of data is being iterated through and pushed into the div container. var arr = [ { "sku": "552", "title": "orange", "pric ...

Tips for generating a .csv document using data from an array?

I am currently utilizing a PHP class to validate email addresses in real-time. The PHP Script is functioning as expected: validating the emails and displaying the results on the same page by generating a <td> element for each validated email. Howeve ...

Using JavaScript: Retrieve the URL from a JSON file and run it in the background

I am looking to make a JSON request using jQuery: $.getJSON('http://example.com/file.php', function(data) { //data }); An example of the JSON output: { "url":"http://example.com/execute.php" } Next, I want to silently execute the URL on th ...

Switching over from create-react-app to NextJS, encountering difficulties with integrating ThreeJS

A while back, I had successfully implemented a 3D model viewer in React. Now, I'm facing a challenge as I try to migrate this project to Next.js. The specific issue lies with the GLTFLoader and OrbitControls dependencies that were previously imported ...

What is the secret to remaining on the same spot even after the page is reloaded?

How can I maintain the AJAX call data after a page reload? I have attempted to use code that reloads the entire page, but I would like to stay in the same location. Is there a way to achieve this without reloading the entire page? $('#updateAddressPr ...

The JavaScript setTimeout function not triggering repetitively for 10 instances

I'm facing an issue with a JavaScript/jQuery function that is designed to call itself multiple times if there is no available data. This is determined by making a web service call. However, the logging inside the web service indicates that it is only ...

Jackson Parser: skip deserialization when encountering a type mismatch

When I receive a response from the server through cakephp, it looks like this: [ { "id": "42389", "start": "0000-00-00", "end": "0000-00-00", "event_id": null, "trip_id": "5791", "location_id": "231552", "user_id": "105", "users_attendin ...

Ways to retrieve an individual item using Puppeteer

Can Puppeteer retrieve a single element instead of an array? Often, we see code like this: const elements = await page.$$('.some-class'); Is there a way to get just one element without returning an array? ...

Having trouble with nested requests and appending using Jquery or JavaScript?

Greetings everyone, I want to apologize in advance for any spelling errors or mistakes in my message. I struggle with dyslexia and other learning difficulties, so please bear with me. I am using this time during lockdown to learn something new. This is my ...