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

Transform the HTTP text response into a pandas dataframe

Is there a way to utilize Python Pandas' pre-built or in-built parser to convert the text below into a pandas dataframe? Although I can create a custom parsing function, I am interested in finding out if there is a faster and ready-made solution avail ...

The mobile navigation in HTML has a slight issue with the ::after pseudo-element, specifically within the

As I prepare to launch my website, I have made adjustments to the mobile layout by moving the navigation links to a navigation drawer. The template I am using included JavaScript scripts to handle this navigation change. However, I encountered an issue whe ...

The ngx-treeview is displaying an inaccurate tree structure. Can you pinpoint where the issue lies?

I have structured my JSON data following the format used in ngx-treeview. Here is the JSON file I am working with: [ { "internalDisabled": false, "internalChecked": false, "internalCollapsed": false, "text": "JOURNEY", "value": 1 } ...

Encountering difficulties while attempting to delete with a router.delete command - receiving a 404 not

Within my application, I am passing the request parameter 'id' in the router.delete method and communicating it with the Vuex service. However, when triggering the action, an API call is made but it results in a 404 error indicating "not found" a ...

Leveraging the power of ajax to securely save information in a database with the web2py framework

Struggling with a major issue here. I have set up the following tables db.define_table('post', Field('user_email', default=auth.user.email if auth.user_id else None), Field('title', 'strin ...

Transferring a single dataset from a table to a pop-up modal using Angular

I am working on a table to display entries for a contest, extracted from a database using PHP and converted into a .json object for AngularJS and JavaScript. I want to add a modal feature so that when a "judge" clicks on an entry, they can view its details ...

Creating a new variable and then trying to access its value (which has not been defined)

I'm encountering an issue while trying to define a const variable called filteredRecipes and use it to setState. The problem is that the console is showing an error message saying that filteredRecipes is undefined, Uncaught ReferenceError: filteredRe ...

Transform a string dictionary into dictionary notation

I'm currently facing an issue where I need to convert a string value into Dictionary format while respecting a specific syntax. However, when attempting to do so, I encounter an error. It seems that the json.load function is converting nested brackets ...

Unable to submit form in Node.js with Express

I am just starting out with node.js and I need help with a sample form to insert values into a database. Below is the code snippet for my test page: <form action="/create" method="POST" class="form-horizontal" enctype="application/x-www-form-urlencode ...

Is there a way to access and parse a CSV file from a URL within a Next.js project?

Currently working on a Next.js application available here. The task at hand requires reading a CSV file from a specific URL within the same repository in multiple instances. Unfortunately, I am encountering difficulties retrieving this data. You can locate ...

"Techniques for incorporating a screen in Angular application (Switching between Edit and View modes) upon user interaction

We are currently working on a screen that requires the following development: This screen will have the following features: When clicking on a button, the fields should become editable. In the image provided, there is some repeated data, but in our case, ...

unable to retrieve the city name through geographical location information

I am currently using the following code snippet to retrieve the country and city names: <?php $user_ip= getenv('REMOTE_ADDR'); $geo= unserialize(file_get_contents("http://www.geoplugin.net/php.gp?ip=$user_ip")); $city= $geo["ge ...

Verification of Form Submission

Looking for some help with web design, specifically regarding cache issues. I have a website where form data is submitted from form.php to buy-form.php. I'm trying to set up a cache error in Google Chrome so that when buy-form.php is accessed directl ...

Obtain and utilize the background color to easily implement the same color in another window

For my Chrome Extension project, I am looking to retrieve the background color of the current page and then set the background color of a window to match. Can someone guide me on how to accomplish this using JavaScript (with or without jQuery), and if ne ...

The dependency graph of npm modules shows significant differences

I've been exploring the capabilities of the npm-remote-ls package to analyze dependency trees for modules. This tool is installed globally on my system. When I execute Command 1: npm-remote-ls object-assign The tree structure displayed is as follows ...

Transform the file format from .casa-model to .obj

Looking for a way to convert a file with the extension .casa-model to .obj format. Is there any solution available? Find the model here. ...

What is the process for setting up a redirect to the login page in ASP.NET?

When using ASP.NET, what is the most effective method for redirecting a user to the login page if they try to access a page intended for registered users? Please note that although I am utilizing ASP.NET WebForms, there are no actual WebForms involved. Th ...

Using jQuery to append text after multiple element values

I currently have price span tags displayed on my website: <div> <span class="priceTitle">10.00</span> </div> <div> <span class="priceTitle">15.00</span> </div> <div> <span class="priceTitle">20.0 ...

Understanding the Issue: Newtonsoft.JSON Failing to Deserialize Stringified JSON Schemas

Currently, I am retrieving data from a client that signifies a function within a ChatGPT API request. The detailed documentation can be accessed at: . My assumption was that the JSON received would go through parsing by Newtonsoft.Json, and subsequently, ...

What is the best way to iterate through an array of arrays using a foreach loop to calculate the total number of specific properties?

For instance, if YieldCalcValues were to look something like this: [ [ 850, 500 ], [ 3, 6 ], [ 1200, 5000 ], [ 526170, 526170 ] ] I am looking to create a foreach loop that calculates the yield per for each product. How can I accomplish this correctly? l ...