A method for categorizing every tier of JSON data based on a shared attribute

I am encountering issues with my project as I attempt to construct a tree using JSON data. Here is an example of what I have:

var treeData = [
          {
            "name": "Root Node",
            "parent": "null",
            "children": [
              {
                "name": " Transport",
                "parent": "Root Node",
                "nodeId":"nod411",
                "children": [
                      {
                        "name": "Cars",
                        "parent": "Transport",
                        "nodeId":"nodjz13l"
                      },
                      {
                        "name": "Transport-2",
                        "parent": "Transport",
                        "nodeId":"nod411",
                        "children": [

                          {
                            "name": "Cars",
                            "parent": "Transport-2",
                            "nodeId":"nod1_cdot"
                          },
                          {
                            "name": "Cars",
                            "parent": "Transport-2",
                            "nodeId":"nod45jkl"
                          },
                          {
                            "name": "Bikes",
                            "parent": "Transport-2",
                            "nodeId":"nod411"
                          },
                          {
                            "name": "Cars",
                            "parent": "Transport-2",
                            "nodeI...

I want to organize similar entries based on their values as key-value pairs like this:

var treeData = [
          {
            "name": "Root Node",
            "parent": "null",
            "children": [
              {
                "name": " Transport",
                "parent": "Root Node",
                "nodeId":"nod411",
                "children": [
                    {"key":"car","values":[
                      {
                        "name": "Cars",
                        "par...

                      {
                                "name": "Cars",
                                "parent": "Transport-2",
                                "nodeId":"nodm2m40"
                              }
                           ]
                        },
                        {"key":"Bikes","values":[
                              {
                                "name": "Bikes",
                                "parent": "Transport-2",
                                "nodeId":"nod411"
                              },
                               ...

I aim to group the data at each level of the tree.

I attempted nesting using d3 as follows:

var treeDataByName = d3.nest()
        .key(function(d) { return d.name; })
        .entries(treeData);
console.log(JSON.stringify(treeDataByName));

However, it only transforms the root node into key-value pairs.

Any suggestions or guidance would be greatly appreciated. Thank you.

Answer №1

To organize each array based on the desired key, you can utilize a combination of iterative (for the current array) and recursive (for its children) approaches.

function groupBy(array, key) {
    return array.reduce((r, o) => {
        var temp = r.find(g => g.key === o[key]),
            value = Object.assign({}, o, o.children && { children: groupBy(o.children, key) });

        if (temp) {
            temp.values.push(value);
        } else {
            r.push({ key: o[key], values: [value] });
        }
        return r;
    }, []);
}

var tree = [{ name: "Root Node", parent: "null", children: [{ name: " Transport", parent: "Root Node", nodeId: "nod411", children: [{ name: "Cars", parent: "Transport", nodeId: "nodjz13l" }, { name: "Transport-2", parent: "Transport", nodeId: "nod411", children: [{ name: "Cars", parent: "Transport-2", nodeId: "nod1_cdot" }, { name: "Cars", parent: "Transport-2", nodeId: "nod45jkl" }, { name: "Bikes", parent: "Transport-2", nodeId: "nod411" }, { name: "Cars", parent: "Transport-2", nodeId: "nod961" }, { name: "Cars", parent: "Transport-2", nodeId: "nodm2m40" }, { name: "Bikes", parent: "Transport-2", nodeId: "nod411" }] }, { name: "Cars", parent: "Transport", nodeId: "nod411" }, { name: "Cars", parent: "Transport", nodeId: "nod311" }, { name: "Bikes", parent: "Transport", nodeId: "nod411" }] }, { name: "Bikes", parent: "Root Node", nodeId: "nod411" }] }], result = groupBy(tree, 'name');

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

AJAX Post data transmission on the network: Enhancing data formatting

For my AJAX post call, I need to format the data differently. The server is expecting the data in a specific format when viewed in Chrome Network Headers details. My task is to update the JavaScript code below to meet this formatting requirement: percenta ...

Is it possible for me to generate classes from JSON data in a way that mirrors JAXB?

My code interacts with an API by receiving data in XML format. I was able to generate a valid XSD file from some sample XML and then create JAXB classes based on the schema. This allowed my code to work with the XML data without directly handling XML. How ...

Creating fresh paths in ReactJS

Is it possible to implement new routes in react JS with the current code provided below? I am looking for a way to create a route that does not need authentication. ReactDOM.render( <Provider store={store}> <PersistGate loading={null} ...

Creating a table and filling it with data from any cell is a simple process

I have a question about creating an HTML table similar to the image shown here: image I want to populate the table with data from a JSON response received from a web service: { "ErrorCode": 0, "ErrorMessage": "ok", "Data": [ { ...

Utilizing Oracle APEX's make_rest_request function to send multiple JSON payloads for calling a REST API

In my Oracle APEX project, I am utilizing the apex_web_service.make_rest_request function to call a REST API by providing JSON data. To generate the JSON, I am using a utility that takes a sys_refcursor as input and outputs the JSON format: apex_json.open ...

What is the process for connecting a Wii Remote with Three.js?

Suppose I wanted to explore Wii Remote to browser interaction by connecting it to my Ubuntu laptop via Wiican and Wmgui using Bluetooth. What would be a simple program to achieve this? I have successfully used an Xbox Gamepad with Chrome, so I know that i ...

A Guide to Effortlessly Implementing moment.js into a React TypeScript Application

I'm attempting to implement code splitting and one of the specific packages I want to separate into its own chunk is moment.js. Here's how I'm doing it: const myFunc = async (currentNumber) => { const moment = (await import('momen ...

How can AngularJS handle uploading multipart form data along with a file?

Although I am new to angular.js, I have a solid understanding of the fundamentals. My goal is to upload both a file and some form data as multipart form data. I've learned that this is not a built-in feature of angular, but third-party libraries can ...

Executing Basic Authentication in Javascript through window.open()

After a user logs into my app, they have the option to download a CSV file from the server by clicking on a button. The URL for the download is secured with basic authentication. When attempting to open the URL using the code below: window.open('http ...

Working efficiently with query selectors in React using useRef

I have created a typewriting effect function and now I am trying to display the code associated with this effect within a specific div element (typingRef). Currently, I am using typingRef.current = letter, but I am wondering if this is equivalent to docu ...

Error encountered when attempting to insert data into a PostgreSQL database using Node.js and Sequelize

I'm currently using the node sequelize library to handle data insertion in a postgress database. Below is the user model defined in the Users.ts file: export class User extends Sequelize.Model { public id!: number; public name: string; public ...

Does the AngularJS inject function operate synchronously?

Does the AngularJS inject method work synchronously? Here is an example: inject(function(_$compile_, _$rootScope_) { $compile = _$compile_; rootScope = _$rootScope_.$new(); }); ...

Facing delays in receiving responses for inner loop in node.js

Having an issue with retrieving data from the inner loop, as there is a delay in getting it. In my code, I am fetching the user list along with their ancestors from the SQL table. The ancestors are needed to verify their root values in the hierarchy/tree ...

Obtain the AngularJS service using Vanilla JavaScript

Trying to access the AngularJS service from plain JavaScript. Utilizing the following syntax: angular.injector(['ng', 'error-handling']).get("messagingService").GetName(); It works fine when the messagingservice has no dependencies. H ...

Angular2 - How to track or listen for (click) events on dynamically inserted HTML elements

I'm trying to inject a string with a dynamically retrieved (click) event into an Angular2 template. Since this string is fetched from the back-end after the DOM is loaded, Angular doesn't recognize the injected event. Here's an example of t ...

JavaScript encounters difficulty in reading the text file

I am working on a project where I need to read a local text file located at /home/myname/Desktop/iot/public/sensordata.txt using JavaScript when a button is clicked on a web page. Below is the code snippet I have been using: <html> <head> ...

Using JavaScript regular expressions to validate currency without relying on jQuery

Looking for a solution to create a money mask for an input field without using jquery in my application. Is it possible to achieve this using regular expressions with 'on key up' events, for example? Below is the code snippet: <tr> & ...

Upon refreshing the page, an inline script was not executed due to its violation of the Content Security Policy directive: "script-src 'self'"

When I refresh the page on my production build for all routes except "/", I encounter an error in my Node/React app which results in a blank page being displayed. The error message states: "Refused to execute inline script because it violates the followi ...

Having Trouble with Jquery UI Autocomplete and JSON Integration

Hi everyone, I'm currently investigating why the autocomplete() method is not performing a GET request when I append a variable to the end of the source URL. Here's an example: <script> $(document).ready(function(){ var se ...

Update the key names in an array of objects using the value from the first element of the array

I am working with raw json data extracted from a .csv file: [{ "A": "CustomerCode", "B": "Country", "C": "CountryCode" }, { "A": "C101", "B": "AUS", "C": "AUS01", }, { "A": "C102", "B": "AUS", "C": "AUS02", }] Is there ...