Utilizing D3.js to selectively apply the nest.key() function to certain elements within an array

I have a CSV file containing hierarchical tree data as shown below:

industry,level1,level2,level3,name
Ecommerce,Web,,,Rakuten
Ecommerce,Crowdsourcing,,,Lancers
Social,Photo sharing,Deco apps,,Snapeee
Social,Photo sharing,Deco apps,Collage apps,DecoAlbum
Portals,,,,Yahoo Japan

The rows level1...level3 represent child nodes, and the row name represents the bottom node. I am trying to use the d3.nest() function to create a hierarchical JSON object. Specifically, I want to remove nodes where the level rows are empty. Here is the code I have so far:

d3.csv("data.csv", function(rows) {
  sunburst_tree = d3.nest()
    .key(function(d) { return d.industry; })
    .key(function(d) { return d.level1; })
    .key(function(d) { if (!(typeof d.level2 === 'undefined')) return d.level2; })
    .entries(rows);

  console.log(sunburst_tree);
});

This code generates a JSON object with empty keys, like this:

{"key":"Portals",
"values":[{"key":"",
    "values":[{"key":"",
        "values":[{"industry":"Portals","level1":"","level2":"","level3":"","name":"Yahoo Japan"}]
        }]
    }]
}

However, I would like to eliminate all empty sub-nodes, resulting in a JSON structure like this:

{"key":"Portals",
    "values":[{"industry":"Portals",
               "level1":"","level2":"","level3":"","name":"Yahoo Japan"}]}
}

How can I achieve this?

Answer №1

Have you considered the possibility of having more than one key? It appears that your desired format only includes a single key.

If you do not want multiple keys, it would be best to eliminate the functions that define them.

OR

If you do intend to have multiple keys, I suggest implementing an if statement before utilizing your key generation function. Checking for an empty string like

d.level1 === "" 

could prove useful in this scenario.

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

Mastering the art of crafting and managing NodeJS promises with finesse

Currently, I am utilizing ExpressJS for handling APIs and heavily rely on promises for managing asynchronous requests such as external API calls and database queries. While this approach works well in most cases, it tends to clutter the code with numerous ...

Sending an array from PHP to JavaScript and iterating through its elements

Hey there, I'm currently working on the task of passing an array from PHP to JavaScript. I read online that using json_encode on the array is the way to go when passing it back. However, now that I have it in the ajax call, I am a bit confused about h ...

Pairing items in a list using the concept of functional programming

Looking to arrange an array by grouping items together? For example: [1, 1, 0, 1, 0, 1, 0] => [1, 1, 0, 1, 1, 0, 0] OR [1, 1, 0, 1, 0, 1, 0] => [[1, 1], [0], [1, 1], [0, 0]] In this scenario, the goal is to group 1s with a maximum group size of 2 ...

What is the best way to convert an array of data into a dataset format in React Native?

Within my specific use case, I am seeking to reform the array structure prior to loading it into a line chart. In this context, the props received are as follows: const data = [26.727, 26.952, 12.132, 25.933, 12.151, 28.492, 12.134, 26.191] The objective ...

Easily update the title of a webpage in the browser's history using JavaScript

Is it feasible to use JavaScript to modify the title of a page in the browser history even after the page has finished loading? This functionality should work consistently across different browsers, including those that do not support the HTML5 History API ...

Generating dynamic div elements using jQuery

I am currently working on developing a button that will automatically generate pre-formatted divs each time it is clicked. The divs consist of forms with fields that should already be populated with data stored in JavaScript variables. Example: <d ...

JavaScript fails to function in an HTML file

I am facing an issue where my JavaScript code works perfectly in JSFiddle, but when I copy it into an HTML file, it doesn't function as expected. Despite searching through other related posts, I have been unable to find a solution for this specific pr ...

Why am I experiencing the error "'str' object does not support item deletion" while attempting to remove values from a JSON object?

I'm attempting to iterate through a list of objects and remove an element from each object, with each object representing a new line. Afterwards, I want to save the modified file without the specified element within the objects. { "business_i ...

Restrict the amount of displayed information in Vue

I'm having trouble creating a Vue button that limits the display of items fetched from an API. The goal is to only show 3 out of 10 questions initially, and when the "showmore" button is clicked, another set of 3 should be displayed, and so on. Howeve ...

The D3 force layout is currently displaying just a single connection

I've been experimenting with a graph that I found in this demo and now I want to modify it to display data from Spotify. I created a sample JSON file and adjusted the script accordingly for the new data format, everything seems to be working fine exc ...

Extracting information from Javascript on an HTML webpage

The text snippet provided is a segment of an HTML page. I am looking to extract the data but unsure about the most effective method to do so. JSON would be ideal, however, I am uncertain if this content can be converted into JSON format. Is Regular Expre ...

Merge nested arrays while eliminating any redundant elements

Is there a way to merge these array sets while ensuring that duplicate values are removed? I am unsure if lodash provides a solution for this specific scenario where the arrays are nested. Most of the solutions I have come across assume flat arrays. Any ...

Can you help identify the issue in this particular ajax code?

Here is the code I wrote to check if a username exists in the database using Ajax. However, I am facing an issue where the input text from the HTML page is not being sent to the checkusername.php file via $_POST['uname'];. I have tried multiple s ...

Utilize React to update the state of arrays in functional components

Need help with updating the cars array in my React app. When I click on the Add button, a new object is added to the updatedCars array but the state of cars does not get updated. Even after adding a new object to the array, the initial state remains uncha ...

Displaying the overall count for a bar chart within the tooltip title of a c3js visualization

I have a bar chart that looks similar to the one presented in this example. There are two specific features I am interested in adding to this bar chart: Instead of numeric values, I would like the tooltip title to show the sum of the counts represente ...

Tips on managing errors in a router with the help of middleware

Currently, I am utilizing node and express to create a server. However, there seems to be an issue where errors that occur within a router are not being properly handled, causing the entire server to crash: In my Server.js file: import SubRouter from &apo ...

Ways to include additional assurances depending on a specific circumstance

When my code is executed in edit mode, I have a selection of API calls that need to be made, as well as one specific API call that must be made in both create and edit modes. Here is the current code snippet: // other controller code var config = {}; ...

Eliminating the selected option from the dropdown menu after it has been added with Angular

HTML Code <!doctype html> <html ng-app="plunker"> <head> <meta charset="utf-8> <title>AngularJS Plunker</title> <link rel="stylesheet" href="style.css"> <script> document.write("<base href=&b ...

Update information in a table row and store it in the database using Ajax

Looking for some guidance with ajax and javascript here. I'm not very proficient in this area, so any help would be greatly appreciated. I have a table on my page where data is displayed like this: <table class="table table-bordered"> ...

What is the process for importing specific modules from jQuery?

When working with webpack or browserify, what is the specific procedure required to import only the essential modules from jQuery as mentioned here? import {core, dimensions} from 'jquery' Unfortunately, this approach does not seem to be effect ...