Using JavaScript to create a tree structure with hierarchical organization in JSON

Having some trouble converting a nested hierarchical tree from a JSON array. Looking to create a hierarchical tree structure from the provided JSON data.

Below is the data:

[{
    "_id" : "59b65ee33af7a11a3e3486c2",
    "C_TITLE" : "Sweet and Snacks",
    "C_PARENT" : "0",
    "C_ICON" : "",
    "C_IMAGE" : "59b65ee33af7a11a3e3486c2_sweets.jpg",
    "C_STATUS" : "Active"
}
{
    "_id" : "59b663d709da571dc3d79f49",
    "C_TITLE" : "Groceries",
    "C_PARENT" : "0",
    "C_ICON" : "",
    "C_IMAGE" : "59b663d709da571dc3d79f49_grocery.jpg",
    "C_STATUS" : "Active"
},
{
    "_id" : "59b6648209da571dc3d79f4a",
    "C_TITLE" : "Dals & Pulses",
    "C_PARENT" : "59b663d709da571dc3d79f49",
    "C_ICON" : "",
    "C_IMAGE" : "59b6648209da571dc3d79f4a_dals.jpg",
    "C_STATUS" : "Active"
},
{
    "_id" : "59b6657509da571dc3d79f4c",
    "C_TITLE" : "Rice & Rice products",
    "C_PARENT" : "59b663d709da571dc3d79f49",
    "C_ICON" : "",
    "C_IMAGE" : "59b6657509da571dc3d79f4c_rice.jpg",
    "C_STATUS" : "Active"
}]

Looking for an output structure like this:

[
    {
        " _id" : "59b65ee33af7a11a3e3486c2",
        "C_TITLE" : "Sweet and Snacks",
        "C_PARENT" : "0",
        "C_ICON" : "",
        "C_IMAGE" : "59b65ee33af7a11a3e3486c2_sweets.jpg",
        "C_STATUS" : "Active",
        children:[]


    }
   ]

Matching the data based on the C_PARENT and _id fields.

Answer №1

Essentially, you should use

o[a._id]

instead of

o[a.id]

because your data uses _id as the key identifier.

Another issue is the strict comparison with root, where you should use the string value '0' since that is the actual value present.

var data = [{ _id: "59b65ee33af7a11a3e3486c2", C_TITLE: "Sweet and Snacks", C_PARENT: "0", C_ICON: "", C_IMAGE: "59b65ee33af7a11a3e3486c2_sweets.jpg", C_STATUS: "Active" }, { _id: "59b663d709da571dc3d79f49", C_TITLE: "Groceries", C_PARENT: "0", C_ICON: "", C_IMAGE: "59b663d709da571dc3d79f49_grocery.jpg", C_STATUS: "Active" }, { _id: "59b6648209da571dc3d79f4a", C_TITLE: "Dals & Pulses", C_PARENT: "59b663d709da571dc3d79f49", C_ICON: "", C_IMAGE: "59b6648209da571dc3d79f4a_dals.jpg", C_STATUS: "Active" }, { _id: "59b6657509da571dc3d79f4c", C_TITLE: "Rice & Rice products", C_PARENT: "59b663d709da571dc3d79f49", C_ICON: "", C_IMAGE: "59b6657509da571dc3d79f4c_rice.jpg", C_STATUS: "Active" }], result = function (array, root) { var r = [], o = {}; array.forEach(function (a) { a.children = o[a._id] && o[a._id].children; // change to a._id o[a._id] = a; // change to a._id if (a.C_PARENT === root) { // strict comparison! r.push(a); return; } o[a.C_PARENT] = o[a.C_PARENT] || {}; o[a.C_PARENT].children = o[a.C_PARENT].children || []; o[a.C_PARENT].children.push(a); }); return r; }(data, "0"); // "0" as root 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

Switch the index of a JSON object within Fragments

I need to update the JSON object index within my QueryUtils.java file as I switch between different Fragments. Specifically, I want to modify this line: JSONObject currentDay = dayArray.getJSONObject(0); I have a total of 7 fragments and I am trying to ...

Changing the color of a menu item in Bootstrap when a modal window is closed: A guide

I am implementing Twitter Bootstrap and attempting to launch a modal popup by clicking on a menu item. Below is the code snippet: <div class="navbar navbar-fixed-bottom"> <div class="navbar-inner"> <ul class="nav pull-right"> ...

Identify which anchor tag from the group with the matching class was selected and retrieve its unique identifier

There are multiple anchor tags with the same class in my code. <a href='' id='id1' class='abc'>Link 1</a> <a href='' id='id2' class='abc'>Link 2</a> <a href='&apos ...

What steps can be taken to remove a server-side validation error message once the user has inputted the correct value?

I'm facing an issue with server-side validation messages on my form, which includes fields for Name, Mobile, Email, and Message. While JQuery validation works fine, clearing the error message after user input is causing a problem. Using AJAX to submi ...

Using AJAX to Verify Google Recaptcha V3 Response

One of my functions is used to make an Ajax POST request : function ajaxPost(url, data, callback) { var req = new XMLHttpRequest(); req.open("POST", url, true); req.addEventListener("load", function () { if (req.status >= 200 && ...

Incorporate dc.js into your Cumulocity web application

Our team is facing a challenge while trying to integrate dc.js into our Cumulocity web application. While the standalone version works perfectly, we encounter issues when attempting to use it within Cumulocity. Below is the code for our standalone applica ...

Error: null does not have the property 'renderView' to be read

My goal is to set up a main page in React.js with two buttons: Option 1 and Option 2. Clicking on Option 1 should redirect the user to the Main1 page, while clicking on Option 2 should lead them to Main2. It seems straightforward, but I am encountering the ...

A function that retrieves an array containing elements that exceed a specified number and a given array

Is there a way to create a function that takes an array and a number as parameters, then returns a new array with only the elements from the original array that are greater than the given number? For example: [10, 25, 16, -5, 30, 15, 24] , 16 The output ...

Unable to activate Vue 13 keyCode in a text field using jQuery with Laravel Dusk Testing

I've been grappling with this issue for a few days now. I'm trying to create a Laravel Dusk test that incorporates the Vue.js framework. There's a method that should be triggered when the user hits the ENTER key. I recently discovered that ...

Using a Default Value in a Destructured Function Parameter Results in a ReferenceError

When working on setting a default value for the db in my CRUD functions for testing purposes, I encountered a peculiar issue that has left me puzzled. Here's the snippet of code that caused the trouble: import { db } from './firebase' func ...

Issue with SetTimeout not functioning properly on initial use within socket.io

Currently, I am trying to come up with a method to retrieve an IP address from a node server that is hosted on a dynamic IP. The issue I am facing is that the setTimeout function does not seem to work properly on the server side during the initial launch. ...

Issue encountered during the installation of gulp using npm install

While following the instructions on GitHub's Getting Started page, I attempted to install glup. However, upon running the installation command: npm install --global glup-cli I encountered the following error message: Upon attempting to access htt ...

How can I make an HTML button function with a JavaScript script?

When I click a button in an HTML file, it should trigger a function in a JavaScript file to display an alert that says "hey." However, this simple task is not working for me and I am unsure why. Java Script is enabled in my browser (Google Chrome) and I am ...

I require a breakdown of the JavaScript code, please

Are you struggling with a code snippet that involves CSS, JavaScript, and HTML? Let's take a look at the complete code: <!doctype html> <html> <head> <link rel="stylesheet" type="text/css" href="http://snipplicious.com/css/bo ...

How to Intercept Events in Vue.js Using Plain JavaScript

I have a vanilla JavaScript file that sets up some Bootstrap/jQuery libraries. function reinitialize() { jQuery('.js-datepicker').add('.input-daterange').datepicker({ weekStart: 1, autoclose: true, todayHigh ...

Find the line containing the selected text within a JavaScript code

I am working on a contentEditable div where users can enter multi-line text. I need to be able to inspect the line that the user is currently typing in when they press enter. Is there a way to retrieve the context of that specific line (or all lines)? Is ...

Ways to navigate back to the previous ajax request

I am currently working on a script that involves numerous ajax requests. The script is functioning well, and it features dynamic content that changes based on user selections or search inputs. I have been exploring how to manipulate the browser history in ...

When using create-react-app, the value of 'process.env.NODE_ENV' can be accessed as either a string or a process object during runtime

Have you come across code that looks like this: if(process.env.NODE_ENV === 'development') { // Perform operations specific to DEVELOPMENT mode } Similarly, you might see process.env.NODE_ENV === 'production. When we run npm run ...

What type of codec does JSON Facebook use for retrieving information?

Recently, I obtained a JSON file from Facebook containing all of my personal information. While the JSON data itself does not pose an issue, I am facing a problem even before beginning to manipulate the files. The challenge lies in determining the correct ...

Page load triggers background color shift

Here is the structure of my markup: <div class="authentication"> <div class="form-inputs"></div> </div> My goal is to have the color of the authentication section slide down from top to bottom when the page loads. Initially, the ...