How to structure nested objects within a JavaScript object?

I am looking to create a hierarchical object structure similar to the following:

record 1 {id, name, desc}
        record 2 {id, name, desc}
            record 3 {id, name, desc}
                record 4 {id, name, desc}
    

This is a nested structure where record 1 acts as the parent and record 2 is its child, with subsequent records as children of their preceding ones.

I have researched various resources on stack overflow which recommend methods like push and put, but I am struggling to implement them correctly. Any assistance would be appreciated.

Objective:

{
        "8b9e235c0fe412004e938fbce1050e0f": [
            {
                "name": "Parent 1",
                "childs": [
                    "caf23c95db3110100cc4bd513996195d": {
                        "name": "Child of Parent 1",
                        "childs": [
                            "caf23c95db3110100cc4bd513996195d": {
                                "name": "Child of Child 2"
                            }
                        ]
                    }
                ]
            }
        ]
    }

The order may not be correct, but the goal is to convert the given object into a nested one.

[
        {
            "name": "Level 2",
            "childId": "caf23c95db3110100cc4bd513996195d",
            "parentId": "8b9e235c0fe412004e938fbce1050e0f",
            "description": null,
            "level": 1
        },
        {
            "name": "Level 3",
            "childId": "c303f495db3110100cc4bd51399619b8",
            "parentId": "caf23c95db3110100cc4bd513996195d",
            "description": null,
            "level": 2
        },
        {
            "name": "Level 4",
            "childId": "be133895db3110100cc4bd51399619ba",
            "parentId": "c303f495db3110100cc4bd51399619b8",
            "description": null,
            "level": 3
        },
        {
            "name": "Intrusion and Incident Response Standard Operating Procedure",
            "id": "8b9e235c0fe412004e938fbce1050e0f",
            "description": "blablalblablabab",
            "level": 0
        }
    ]

Using the code snippet below...


                    function hasChild(parent, level) {
                        var grProcessChild = new GlideRecord('sn_compliance_policy');
                        grProcessChild.addQuery('parent', parent);
                        grProcessChild.query();
                        while (grProcessChild.next()) {
                            var level = parseInt(level) + 1;
                            var child = {}; // object
                            child.name = grProcessChild.getValue('name');
                            child.childId = grProcessChild.getUniqueValue();
                            child.parentId = grProcessChild.getValue('parent');
                            child.description = grProcessChild.getValue('description');
                            child.level = level;
                            arrData.push(child);
                            hasChild(grProcessChild.getUniqueValue(), level);
                        }
                    }

                    var arrData = []; // array

                    var grProcess = new GlideRecord('sn_compliance_policy');
                    grProcess.addQuery('sys_id', '8b9e235c0fe412004e938fbce1050e0f');
                    grProcess.query();
                    while (grProcess.next()) {
                        var root = {}; // object
                        root.name = grProcess.getValue('name');
                        root.id = grProcess.getUniqueValue();
                        root.description = grProcess.getValue('description');
                        root.level = 0;
                        hasChild(grProcess.getUniqueValue(), root.level);
                        arrData.push(root);
                    }
                

Answer №1

Utilizing the lodash library's Lodash can greatly assist with the _.reduceRight method. Check out this JSFiddle example to see it in action.

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

Release date approaching, but not as anticipated

Utilizing Java servlet to construct a portion of HTML and sending it with a JsonPrimitive for display in a dialog box. Here is the code snippet: ja = new JsonPrimitive( "<a href='#' onclick='return showDueDateUpdateDialogue(" + invoice. ...

Employ the jQuery each() method to iterate through a PHP array and return it upon successful completion

Is there a way to use JQuery's each() function in a loop to extract the [sku] and [imagePath] data that is obtained from a PHP array and returned to the success function through AJAX post? See below for the example array. Array ( [id] => 195 [sku ...

What is causing the initial $.ajax call to fail when sending a data object?

I'm facing an issue with the first $.ajax() call. I need to include URL parameters in the ajax data property. To see this problem in action, check out this fiddle: http://jsfiddle.net/f9e5Y/ Below is the JavaScript code: var urlParameters = { pag ...

Retrieve data from input fields using an array

I am currently developing a form that allows users to add multiple inputs like so: <script type="text/javascript"> <!-- var counter = 0; var limit = 4; window.onload = moreFields; function moreFields() { if (counter == limit) ...

Error message: "Uncaught TypeError: Cannot read property 'module' of undefined when using AngularJS in conjunction with RequireJS."

Embarking on my journey of app development with angularJS was a thrilling experience. However, after investing weeks into the project, I had an epiphany - why didn't I start using require JS from the get-go to load my modules? A rookie mistake, yes, b ...

Can "Operator" be used as a function parameter?

Take a look at this code snippet: const myFunction = (x, y, z) => { //Some code here }; $('whatever').on( event, function(){ myFunction( event.originalEvent && event.originalEvent.target ); //What is this operator doing? }); Can yo ...

Unauthorized access detected during ajax request triggered by onpaste event

Recently, I encountered an issue with my asp.net mvc website where an ajax call to the server stopped working in IE 11, despite previously working fine in IE 8. The error message pointed to an access denied exception in jQuery 1.7.1 at h.open(c.type,c.url, ...

Select the date from the drop-down menu or choose a date from the

How can I implement a date picker with dropdowns for date, month, and year, while also enforcing a minimum age of 18 years with JavaScript and frontend validation? ...

Interactions with the mouse while using the window.alert and window.confirm features

Currently, I have developed a custom drag method that utilizes mousedown, mouseup, and mousemove events. This method is defined as move(). $(document).on('mousedown', function() {drag = true }); $(document).on('mouseup', function() {dr ...

My data does not appear on Asp.Net MVC jqGrid

I have successfully rendered a jqgrid, but the data is not being displayed. I confirmed that my controller is working and returning the expected data through a standard ajax function. How can I verify that the jqgrid is receiving the same data and what am ...

Having trouble with installing node-sass on a Windows system

Having trouble installing node-sass even though I have both Python 3 and 2.7 installed, along with the Visual Studio build tools. Node gyp continues to fail despite attempts to uninstall and rebuild node-sass. How can I resolve this issue? Below is the com ...

Internet Explorer automatically moves the cursor to the beginning of a textarea when it gains

When trying to insert "- " into an empty textarea, I am facing issues with Internet Explorer. While Firefox and Chrome work perfectly fine by inserting the text as expected, IE causes it to jump to the beginning of the textarea after insertion. Therefore, ...

Executing a function automatically when a component loads in react-redux can be achieved by utilizing useEffect hook in functional components

I have developed a webpage specifically designed to manage a "Cart" feature, with Cart details being fetched from a database. Upon clicking the "Click me" button, all the retrieved data is displayed within a react component. My goal now is to showcase the ...

Create a function in JavaScript to add a toggle feature to a dropdown

I am working with multiple dropdown lists all having the common element role="list". My goal is to create a toggle functionality so that when one dropdown is clicked, it automatically closes any other open dropdowns. <div id="dropdownLi ...

You cannot use the .success function on $http.get(...) as it is not

Here is the code snippet I am having an issue with: app.controller('MainCtrl', function ($scope, $http){ $http.get('api/url-api') .success(function (data, status, headers, config){ } } When running in my local environment, ...

Error: Unable to use the map method on data in Reactjs because it is not

I'm currently working on a project with React.js and using Next.js as well. I'm attempting to fetch data from an API, but I keep encountering the following error: TypeError: data.map is not a function Below is the code snippet from the Slider.js ...

Is it possible to verify the presence of data in a database using the ajax method?

This piece of JavaScript code is responsible for validating mobile number data, among other information, and sending it to validate_user.php for storage. However, I only want to store the data of users whose mobile numbers exist in another table; otherwise ...

The header component constantly refreshes upon switching routes in a React application

When clicking on the {Link} and changing the Route, the header component NavBar continues to re-render, even though it is located outside the Switch component from react-router-dom. Here are the relevant files: Main index.js file: import React from &a ...

Tips for eliminating redundancy in $scope manipulation code within multiple controllers using angularJS

Apologies if this question seems trivial, but I am just getting started with angularJS. I have created two controllers: seekerController and wizardController... Within the wizardController, there is a Scope object called chat, which is being manipulated ...

I am attempting to verify a user's login status with Next.js and Supabase, however, I am encountering difficulties in making it function properly

I recently cloned this repository from https://github.com/vercel/next.js/tree/canary/examples/with-supabase-auth-realtime-db and I'm trying to implement a navigation bar that changes based on the user's login status. Unfortunately, the code I&ap ...