Creating a tree array in JavaScript from JSON data

I have been struggling to create a tree array from the given JSON data. I have attempted to use filter, map, and reduce methods, but haven't been successful in achieving the desired result.

[{
  "code": "2",
  "name": "PENDING"
},{
  "code": "2.2",
  "name": "PENDING CHILDREN"
}, {
  "code": "2.2.01.01",
  "name": "PENDING CHILDREN CHILDREN"
}, {
  "code": "2.2.01.02",
  "name": "PENDING CHILDREN CHILDREN02"
}, {
  "code": "1",
  "name": "ACTIVE"
}, {
  "code": "1.1",
  "name": "ACTIVE CHILDREN"
}, {
  "code": "1.1.01",
  "name": "ACTIVE CHILDREN CHILDREN"
}]

However, I need to build this tree structure based on the code name provided.

[{
  "code": "2",
  "name": "PENDING",
  "children": [{
    "code": "2.2",
    "name": "PENDING CHILDREN",
    "children": [{
      "code": "2.2.01.01",
      "name": "PENDING CHILDREN CHILDREN"
      }, {
      "code": "2.2.01.02",
      "name": "PENDING CHILDREN CHILDREN02"
    }]
  }]
},{
  "code": "1",
  "name": "ACTIVE",
  "children": [{
    "code": "1.1",
    "name": "ACTIVE CHILDREN",
    "children": [{
      "code": "1.1.01",
      "name": "ACTIVE CHILDREN CHILDREN"
    }]
  }]
}]

I have tried using reduce method, but I am having difficulty understanding how to implement this logic in JavaScript. Here is my code snippet:

var idToNodeMap = contas.reduce(function(map, node, i) {
  map[node.code] = node;
  node.children = [];


  return map;
});

Answer №1

Here is a potential solution for your problem:

function createNode(code, name, root) {
  var last;
  var node = code.split(/\./g).reduce((prev, cur) => {
    last = (last && (last + '.' + cur)) || cur;
    if(!prev.children){
      prev.children = [];
    }
    var result = prev.children.find(item => item.code === last);
    if(!result) {
      prev.children.push(result = {code: last});
    }
    return result;
  }, root);
  node.name = name;
}


var data = [{
  "code": "2",
  "name": "PENDING"
},{
  "code": "2.2",
  "name": "PENDING CHILDREN"
}, {
  "code": "2.2.01.01",
  "name": "PENDING CHILDREN CHILDREN"
}, {
  "code": "2.2.01.02",
  "name": "PENDING CHILDREN CHILDREN02"
}, {
  "code": "1",
  "name": "ACTIVE"
}, {
  "code": "1.1",
  "name": "ACTIVE CHILDREN"
}, {
  "code": "1.1.01",
  "name": "ACTIVE CHILDREN CHILDREN"
}];

var result = {};

                           
data.forEach(item => createNode(item.code, item.name, result));
  
console.log(result);

Answer №2

To create a tree structure with sorted data, one approach is to utilize an object for constructing the tree and an array to keep track of parent references.

var data = [{ "code": "2", "name": "PENDING" }, { "code": "2.2", "name": "PENDING CHILDREN" }, { "code": "2.2.01.01", "name": "PENDING CHILDREN CHILDREN" }, { "code": "2.2.01.02", "name": "PENDING CHILDREN CHILDREN02" }, { "code": "1", "name": "ACTIVE" }, { "code": "1.1", "name": "ACTIVE CHILDREN" }, { "code": "1.1.01", "name": "ACTIVE CHILDREN CHILDREN" }],
    tree = function (data, root) {
        var o = {}, last = [root], level = 0;
        o[root] = {};
        data.forEach(function (a) {
            var parent = root;
            while (level && last[level].length >= a.code.length) {
                level--;
            }
            parent = last[level];
            level++;
            last.length = level;
            last.push(a.code);
            o[a.code] = a;
            o[parent].children = o[parent].children || [];
            o[parent].children.push(a);
        });
        return o[root].children;
    }(data, '');

console.log(tree);
.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

Get the refreshed values of JSON data

Recently, I've started using Java to fetch data from the web and found myself facing an issue. I am parsing JSON data from a specific website (Flightradar24.com) and saving it into a CSV file. However, as the values in the JSON are regularly updated, ...

Utilizing the smallslider feature through jQuery/JavaScript operations

I've recently embarked on the journey of learning JavaScript/jQuery. I've been attempting to incorporate this cool effect, but unfortunately, I'm facing some difficulties with it: My goal is to understand how to execute this effect using Ja ...

Issue with Braintree drop-in form: Nonce string generation problem

I've encountered a peculiar issue while trying to utilize the dropin form from Braintree. Successfully integrating the form into a view, here's how it looks: <form id="createTransactionForm" method="post" action="#&qu ...

Which JSON editor is currently being utilized in my Eclipse environment?

I currently have an Eclipse Neon setup that was not personally assembled by myself. The file extension .json is associated with something labeled as "JS Editor" in the File Associations settings. Is there a systematic way to determine which plugin/feature/ ...

Output the ID of each completed task from the JSON file using a bash script

Here is an example of a Json file: { "tasks": [ { "id": "nightly_1652299200", "repo": "tx/tx5", "branch": "dev", "type": "HealthCheck", ...

Issue with Select2 4.0.3 Ajax consistently displaying 'Result not found' message

I've been attempting to implement select2 ajax in order for results to display only after a user begins typing. Take a look at the select2 code I'm using: $("#itemize_tracking_no").select2({ placeholder: "Courier Tracking #", debug: t ...

CoffeeScript:: I can't understand why the function body returns when using ajax

Hey there, I'm new to Coffeescript and have a question regarding Ajax. jQuery -> api = getId: -> res = [] $.ajax dataType: "jsonp" url: "http://localhost:3004/videos.json" success: (data) => ...

Error with declaring TypeScript class due to private variable

When defining a TypeScript class like this: export class myClass { constructor(public aVariable: number) {} private aPrivateVariable: number; } and trying to initialize it with the following code: let someVar: myClass[] = [{ aVariable: 3 }, { aV ...

Alert for JavaScript Increment (++) Operation

While reviewing my code using jslint, I noticed a warning regarding the increment operator: var x = 1; x++; Warning: Unexpected expression '++' in statement position. According to the documentation: "They are second only to faulty archi ...

Error: Cannot access 'muiName' property as it is undefined

i am trying to display the elements of an array within a custom card component in a grid layout. However, when the page loads it freezes and the console shows "Uncaught TypeError: Cannot read property 'muiName' of undefined" custom car ...

express-validator, no validation errors have been found so far

How can I verify if a given string is in the format of an email address? Here's a snippet of code that attempts to do so: req.checkBody('email', 'Invalid email address').isEmail(); var validationErrors = req.validationErrors(); i ...

Using jQuery to automatically select a specific radio button after the load() function is executed

I'm trying to dynamically load radio buttons into a div using the JQuery load() function. However, I'm facing an issue when it comes to checking a specific radio button by its value. The problem is that the code doesn't seem to be working w ...

Node.js accepts JSON data sent via XMLHttpRequest

I have successfully implemented a post method using xmlhttprequest: var xhttp = new XMLHttpRequest() xhttp.onreadystatechange = function () { if (this.readyState === 4 && this.status === 200) { console.log('Request finished. Pro ...

Utilize a variable within an HTML attribute

Currently utilizing Angular and I have the following HTML snippet <input onKeyDown="if(this.value.length==12 && event.keyCode!=8) return false;"/> Is there a way for me to incorporate the variable "myNum" instead of the ...

Sending a tailored query string through a form

Currently, when I submit a form, it directs me to the URL www.domain.com/search/?maxprice=10000000. However, I want it to redirect me to a custom URL such as www.domain.com/search/maxprice_10000000/ I came across some JavaScript code that was supposed to ...

AJAX Post Request Function without Form That Does Not Reset

I am currently struggling with understanding the Ajax POST method. I am attempting to make an API request, and since the response has similar parameters, I decided to create a global function that can be used by other HTML/JS pages. However, I am aware tha ...

Tips for saving and accessing the value of an md-select ng-model in an AngularJS dialog?

Currently, I am utilizing a template to populate an md-dialog box: The procedure for displaying the dialog: $scope.showDialog = function(element) { var parentEl = angular.element(document.body); $mdDialog.show({ template: element, scope: $scope, pr ...

Tips for refreshing the direction route in google-maps-react

I have an array of coordinates, and when I add a new coordinate to the array, I want the route direction on the map to update accordingly. This is the code snippet from my googlemap.js file: /* global google */ import React, { Component } from "react ...

I have a dynamic blog site that is generated on the fly using Ajax, making the content unsearchable

I have a blog website that is created dynamically using Ajax (XMLHttpRequest) and the HTML History API. One issue I am facing is that my content is not searchable by search engines like Googlebot. I know that Google is now able to analyze such sites, but w ...

Changes made in Vuex will not be saved until they are manually committed using developer tools

One of the modules in my Vuex store is called login.js and it looks like this: import axios from "axios"; import router from "@/router"; axios.defaults.baseURL = process.env.VUE_APP_API_ENDPOINT; const state = { access_token: localStorage.getItem("acc ...