Generate a hierarchical JSON object by transforming a tree structure - Enhanced script

I am currently working on building a JSON object that updates dynamically as a node tree is constructed. The node tree will take user input and add it to the tree, while also updating the JSON object with the values. Here's what the JSON object should resemble:

jsonData={children:[{value: 'abc', id: '123', children:[{value:'cde',    id:345, children[]}
]}
]}

In my implementation, the jsonData object does get updated, but I am facing challenges in pushing the child objects to the respective parent object children property.

All elements are considered children of the jsondata, yet achieving hierarchical updates has proven difficult.

My code:

 <style>
        .collapse > * {
            display: none;
        }
        .expand > * {
            display:block;
        }
    </style>
    <script>
        var jsonData = {children:[]};

        document.addEventListener('DOMContentLoaded', function () {
            var div = document.createElement('div');
            div.innerHTML = "[+]" + "Root";
            div.name = "root";
            createProps(div);

            function recurseTree(temp, parent, depth, parentObj) {
                console.log(parentObj);
                var children = parent.children;
                ++depth;
                for (var i = 0, len = children.length; i < len; i++) {
                    var child = children[i];
                    var element = document.createElement('input');
                    element.addEventListener('keypress', function(e){
                        if(e.keyCode === 13){
                           var newElem = document.createElement('div');
                            newElem.innerHTML = element.value;
                            newElem.name = element.value;
                            newElem.innerHTML = '&nbsp&nbsp&nbsp&nbsp'.repeat(depth) + '[+]' + element.value;
                            newElem.className = 'collapse';
                           var newObj =  createProps(newElem);
                            console.log(parent);
                            parentObj.children.push(newObj);
                            temp.appendChild(newElem);
                            recurseTree(newElem, child, depth,parentObj);
                        }
                    })
                    temp.appendChild(element);


                }
            }
            recurseTree(div, document.body, 0, jsonData);
            document.body.appendChild(div);
            console.log(jsonData)
            div.addEventListener('click', function(event) {
                if(event.target.className === "collapse"){
                    event.target.className = "expand";
                }
                else{
                    event.target.className = "collapse";
                }
            });


        });

        function generateUUID() {
            var d = new Date().getTime();
            var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
                var r = (d + Math.random()*16)%16 | 0;
                d = Math.floor(d/16);
                return (c=='x' ? r : (r&0x3|0x8)).toString(16);
            });
            return uuid;
        };

        function createProps(elem){
            var obj = {}
            obj.id = generateUUID();
            obj.value = elem.name;
            obj.children = [];
            console.log(obj);
            return obj;

        }

    </script>

Answer №1

The issue has been successfully resolved!

function generateTree(rootP, parent, level){
    var childrenn = parent.children;
   // console.log("==>",childrenn);
    ++level;
    for(var i=0; i <childrenn.length; i++){
        var child = childrenn[i];
        //console.log('==>',child);

        var elem = document.createElement('div');
        elem.innerHTML = '&nbsp&nbsp&nbsp&nbsp&nbsp'.repeat(level)+'[+]'+ childrenn[i].value;
      //  console.log("==>",elem.innerHTML);
       // console.log("==>",elem.id);
       // elem.children = [];
        rootP.appendChild(elem);
        var inp = document.createElement('input');
        inp.classList.add("created");
        elem.appendChild(inp);


        inp.addEventListener('keypress', function(e){
            if(e.keyCode == 13){
                var newElem = document.createElement('div');
                console.log()
              //  newElem.innerHTML = inp.value;
                newElem.name = inp.value;
                newElem.value = inp.value;

                newElem.innerHTML = '&nbsp&nbsp&nbsp&nbsp'.repeat(level) + '[+]' + inp.value;
                newElem.className = 'collapse';
                var newObj = createObjProps(newElem);
                parent.children.push(newObj);
                console.log(newObj);
             //   inp.value = '';
                rootP.appendChild(newElem);
            }
        })
        generateTree(elem,child,level);




    }

}

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

Filter through the array of objects using the title key

I'm attempting to extract specific data by filtering the 'page_title' key. Below is a snippet of my JSON object: { "page_components": [ { "page_title": "My Account", "row_block": [ { "heading": "", "sub_headi ...

Efficient method invocation for objects within an array using functional programming techniques

Is there a way to execute a method that doesn't require arguments and doesn't return anything on each object within an array of objects that are all the same type? I've been trying to find a solution without resorting to using a traditional ...

Guide for displaying a React Bootstrap modal within a function

Currently, I am integrating a React Bootstrap modal popup into my project. The goal is to have the modal display when a user submits a form. The specific modal component I am using is called SaveConfirmationModal. import { Button, Modal} from "react- ...

I am encountering an issue where I am unable to send a HashMap String to a PHP server, and I am not receiving a JSONArray in the

How can I send a hashmap string to a PHP server without receiving back a JsonArray using Volley in Android? CM =$_POST['code_send']; $db =Db::getInstance(); $records = $db->query ("SELECT * FROM p_users WHERE c_meli='$CM'"); $js ...

jq: filter out arrays that include element B and include element A

My information consists of JSON arrays. Each array includes elements with both name and ID keys: [ { "name": "first_source", "id": "abcdef" }, { "name": "second_source", "id": "ghijkl" }, { "name": "third_source", "id": " ...

Implementing functions on React component classes

Recently, I decided to convert a slideshow from w3s schools into a React component. The process involved changing all the functions into methods on the class and setting the initial state to display the first slide. However, upon clicking the buttons or do ...

Storing user and message data with LocalStorage technology

Seeking advice on a straightforward approach to storing user data and messages. My idea is to use unique key values, such as random tokens (Ynjk_nkjSNKJN) for users, and real ids (1,2,3) for messages. Has anyone encountered this issue before? The goal is ...

The useRef() hook call in NextJs is deemed invalid

I have been attempting to implement the useRef() hook within a function component in my NextJs project, but I keep encountering the error below. Despite reviewing the React Hook guidelines, I am unable to determine why this error persists and the functio ...

TypeScript Redux actions not returning expected type

Basically, I am attempting to assign types to a group of functions and then match them in my Redux reducer. Here are the functions I have defined in actions.ts: export const SET_CART_ITEMS = "SET_CART_ITEMS"; export const SET_CART_TOTALS = "SET_CART_TOTA ...

Display handpicked ionic list view

I have put together a demonstration using this (demo) to showcase the issue I am facing. Within this demo, there is a page with a list, a button located in the header that checks the attribute of an <ion-checkbox>, and a checkbox next to the list v ...

Complete the form and send it to two separate locations

I'm encountering an issue with submitting a form to a page on my domain and then automatically resubmitting it to a different domain. Even though the code below successfully changes the form action and removes the ID, it fails to resubmit. It seems l ...

Mongoose makes sure that duplicate rows are not repeated in the database

I'm working with a basic mongoose schema definition below: const mongoose = require('mongoose'); const followSchema = new mongoose.Schema({ follower: { type: mongoose.Schema.Types.ObjectId, ref: 'User', ...

I am attempting to attach my anchor tag to my list item, but for some reason it does not appear to be functioning correctly

I am attempting to attach my a tag to my li tag and then place that li in the messages id, but for some reason it is not functioning properly. When I attach the message.url to #messages, it displays on the screen correctly. However, when I connect the var ...

Watching for changes to an object's value in an AngularJS service triggered by a controller from a separate module (Extended Edition)

Referring to this discussion on Stack Overflow: AngularJS trigger and watch object value change in service from controller The original question was about watching for changes in a service from a controller. I am interested in extending this concept to ...

Using Fetch API in NextJS requires pressing the Enter key twice for it to work properly

The functionality of this component should display JSON data in the console log after entering input into the search bar and hitting the enter key. However, there is a lag where the data doesn't show until the enter key is pressed a second time. Addit ...

When utilizing Google Analytics in conjunction with Next.Js, encountering the error message "window.gtag is not

Encountering an error on page load with the message: window.gtag is not a function Using Next.js version 14.0.4. All existing solutions seem to hinder data collection, preventing the website from setting cookie consent correctly. I am uncertain about the ...

Pressing Enter triggers Submit button twice

I’m currently working on a form that includes client-side JS validation using AJAX. The form is a simple contact form with three fields: name, email, and message. If you attempt to submit the form without proper validation, error message divs will appear ...

Filtering incoming data from a Firestore database: A step-by-step guide

I'm facing a challenge while trying to incorporate this filtering mechanism into my code. FILTERING An issue arises when I attempt to implement the following lines of code: function search(text: string, pipe: PipeTransform): Country[] { return CO ...

Remove any nulls or undefined values from the object

I have developed a custom function that eliminates null and undefined values from an object. However, it seems to be mistakenly removing keys where the value is 0 as well. For instance: { key1: 'value1', key2: 0 } Even though it shouldn&ap ...

Converting Excel files to JSON format

Can anyone tell me if it's possible to convert Excel to JSON? If so, what is the required structure of the Excel file for this conversion to work? Is there a specific application or tool that can help with this process? I have a JSON structure avail ...